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 do I delete a file or folder in Python?
6,996,603
691
2011-08-09T13:05:42Z
6,996,628
1,162
2011-08-09T13:07:39Z
[ "python", "file-io", "folder", "windows-xp", "delete-file" ]
How do I delete a file or folder in Python? I am using the Python scripting language running on the Windows XP operating system.
[`os.remove()`](http://docs.python.org/library/os.html#os.remove) will remove a file. [`os.rmdir()`](http://docs.python.org/library/os.html#os.rmdir) will remove an empty directory. [`shutil.rmtree()`](http://docs.python.org/library/shutil.html#shutil.rmtree) will delete a directory and all its contents.
How do I delete a file or folder in Python?
6,996,603
691
2011-08-09T13:05:42Z
6,996,662
37
2011-08-09T13:09:48Z
[ "python", "file-io", "folder", "windows-xp", "delete-file" ]
How do I delete a file or folder in Python? I am using the Python scripting language running on the Windows XP operating system.
Use ``` shutil.rmtree(path[, ignore_errors[, onerror]]) ``` (see complete doc on [shutil](http://docs.python.org/library/shutil.html)) and/or ``` os.remove ``` and ``` os.rmdir ``` (complete doc on [os](http://docs.python.org/library/os.html#os.remove))
How do I delete a file or folder in Python?
6,996,603
691
2011-08-09T13:05:42Z
39,079,453
11
2016-08-22T12:22:19Z
[ "python", "file-io", "folder", "windows-xp", "delete-file" ]
How do I delete a file or folder in Python? I am using the Python scripting language running on the Windows XP operating system.
## For deleting files: You can use [`unlink`](https://docs.python.org/3/library/os.html#os.unlink) or [`remove`](https://docs.python.org/3/library/os.html#os.remove). ``` os.unlink(path, *, dir_fd=None) ``` Or ``` os.remove(path, *, dir_fd=None) ``` This functions `Remove (delete) the file path`. If path is a dire...
Python causing: IOError: [Errno 28] No space left on device: '../results/32766.html' on disk with lots of space
6,998,083
5
2011-08-09T14:46:23Z
6,999,259
18
2011-08-09T16:04:38Z
[ "python", "filesystems", "hard-drive" ]
I am running a Python script that is causing the above error. The unusual thing is this script is running on a different machine and is having no problems. The difference is that on the machine that is causing the problems I am writing to an external hard drive. To make things even weirder this script has run on the p...
The `ENOSPC` ("No space left on device") error will be triggered in *any* situation in which the data or the *metadata* associated with an I/O operation can't be written down anywhere because of lack of space. This doesn't always mean disk space – it could mean physical disk space, logical space (e.g. maximum file le...
Django templates: forloop.first and forloop.last
6,998,366
28
2011-08-09T15:04:45Z
7,000,036
18
2011-08-09T17:08:45Z
[ "python", "django" ]
I have the following code in my template: ``` {% for f in friendslist %} {% if forloop.first %} // display something {% endif %} // display stuff {% if forloop.last %} // display something {% endif %} {% endfor %} ``` It w...
In my code they both execute if there is only one element in friendslist. Here is a test you can run in the shell where maybe you can figure out what isn't working: ``` $ ./manage.py shell >>> from django import template >>> t = template.Template("""{% for f in friendslist %} {% if forloop.fi...
Celery: standard method for querying pending tasks?
6,998,377
7
2011-08-09T15:05:31Z
7,009,592
8
2011-08-10T10:48:10Z
[ "python", "celery" ]
Is there any standard/backend-independent method for querying pending tasks based on certain fields? For example, I have a task which needs to run once after the “last user interaction”, and I'd like to implement it something like: ``` def user_changed_content(): task = find_task(name="handle_content_change")...
No, this is not possible. Even if some transports may support accessing the "queue" out of order (e.g. Redis) it is not a good idea. The task may not be on the queue anymore, and instead reserved by a worker. See this part in the documentation: <http://docs.celeryproject.org/en/latest/userguide/tasks.html#state> Gi...
How can I make python 2.6 my default in Mac OS X Lion?
6,998,545
10
2011-08-09T15:17:11Z
7,000,324
70
2011-08-09T17:32:09Z
[ "python", "osx", "osx-lion" ]
I just upgraded to lion and with it came Python 2.7. I need to use 2.6 as my default python as the project I primarily work on uses 2.6.
Apple has provided two very simple ways to change the default python on OS X 10.6 Snow Leopard and 10.7 Lion. It's all detailed in the Apple man page for python(1): ``` $ man python $ which python /usr/bin/python $ python -V Python 2.7.1 # # temporarily change version # $ export VERSIONER_PYTHON_VERSION=2.6 $ python -...
In matplotlib, how do you display an axis on both sides of the figure?
6,998,697
7
2011-08-09T15:27:12Z
12,651,723
21
2012-09-29T09:52:21Z
[ "python", "graphics", "matplotlib", "plot" ]
I want to draw a plot with matplotlib with axis on both sides of the plot, similar to this plot (the color is irrelevant to this question): ![plot](http://i.stack.imgur.com/gHYKk.gif) How can I do this with `matplotlib`? Note: contrary to what is shown in the example graph, I want the two axis to be exactly the same...
You can use [tick\_params()](http://matplotlib.org/api/axes_api.html?highlight=tick_params#matplotlib.axes.Axes.tick_params): ``` bar(range(10), range(10)) tick_params(labeltop=True, labelright=True) ``` Generates this image: ![Bar plot with both x and y axis labeled the same](http://i.stack.imgur.com/Z0U9p.png)
Using sqlite prepared statements with SELECT
6,998,968
2
2011-08-09T15:45:34Z
6,999,052
7
2011-08-09T15:50:56Z
[ "python", "sqlite" ]
I'm working on a little pet project that organizes people's comic books and stores metadata about them in an SQL database. For the sake of correctness, I'm using prepared statements instead of Python's built in string operators, but I can't quite get it to work right. This is a brief snippet of code I've made to illust...
You can't use placeholders for column names - they are for values only. So this would work: ``` cmd = "SELECT * from comic_collection WHERE %s LIKE ?" % attribute curs.execute(cmd, (val,)) ```
Python line-by-line memory profiler?
6,999,522
29
2011-08-09T16:27:16Z
7,057,953
13
2011-08-14T16:03:39Z
[ "python", "memory", "profiling" ]
I'm looking to generate, from a large Python codebase, a summary of heap usage or memory allocations over the course of a function's run. I'm familiar with [heapy](http://guppy-pe.sourceforge.net/), and it's served me well for taking "snapshots" of the heap at particular points in my code, but I've found it difficult ...
I would use [`sys.settrace`](http://docs.python.org/library/sys.html#sys.settrace) at program startup to register a custom tracer function. The custom\_trace\_function will be called for each line of code. Then you can use that function to store information gathered by heapy or [meliae](https://launchpad.net/meliae) in...
Python, HTTPS GET with basic authentication
6,999,565
23
2011-08-09T16:31:22Z
6,999,774
11
2011-08-09T16:47:49Z
[ "python", "python-3.x" ]
Im trying to do a HTTPS GET with basic authentication using python. Im very new to python and the guides seem to use diffrent librarys to do things. (http.client, httplib and urllib). Can anyone show me how its done? How can you tell the standard library to use?
Update: OP uses Python 3. So adding an example using [httplib2](http://code.google.com/p/httplib2/) ``` import httplib2 h = httplib2.Http(".cache") h.add_credentials('name', 'password') # Basic authentication resp, content = h.request("https://host/path/to/resource", "POST", body="foobar") ``` The below works for ...
Python, HTTPS GET with basic authentication
6,999,565
23
2011-08-09T16:31:22Z
7,000,784
32
2011-08-09T18:12:57Z
[ "python", "python-3.x" ]
Im trying to do a HTTPS GET with basic authentication using python. Im very new to python and the guides seem to use diffrent librarys to do things. (http.client, httplib and urllib). Can anyone show me how its done? How can you tell the standard library to use?
In Python 3 the following will work. I am using the lower level [http.client](http://docs.python.org/py3k/library/http.client.html) from the standard library. Also check out section 2 of [rfc2617](http://www.ietf.org/rfc/rfc2617.txt) for details of basic authorization. This code won't check the certificate is valid, bu...
How to assign a string value to an array in numpy?
6,999,617
4
2011-08-09T16:34:30Z
7,000,376
10
2011-08-09T17:37:57Z
[ "python", "numpy" ]
When I try to assign a string to an array like this: ``` CoverageACol[0,0] = "Hello" ``` I get the following error ``` Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> CoverageACol[0,0] = "hello" ValueError: setting an array element with a sequence. ``` However, assigning an integer...
You get the error because NumPy's array is [homogeneous, meaning it is a multidimensional table of elements all of the same type](http://www.scipy.org/Tentative_NumPy_Tutorial#head-d3f8e5fe9b903f3c3b2a5c0dfceb60d71602cf93). This is different from a multidimensional list-of-lists in "regular" Python, where you can have ...
how to use 'extent' in matplotlib.pyplot.imshow
6,999,621
16
2011-08-09T16:34:54Z
7,000,381
16
2011-08-09T17:38:13Z
[ "python", "plot", "matplotlib" ]
I managed to plot my data and would like to add a background image (map) to it. Data is plotted by the long/lat values and I have the long/lat values for the image's three corners (top left, top right and bottom left) too. I am trying to figure out how to use 'extent' option with imshow. However, the examples I found ...
Extent defines the images max and min of the horizontal and vertical values. It takes four values like so: `extent=[horizontal_min,horizontal_max,vertical_min,vertical_max]`. Assuming you have longitude along the horizontal axis, then you'll take `extent=[longitude_top_left,longitude_top_right,latitude_bottom_left,lat...
How can I convert a datetime object to milliseconds since epoch (unix time) in Python?
6,999,726
163
2011-08-09T16:43:08Z
6,999,787
57
2011-08-09T16:48:48Z
[ "python", "datetime", "epoch" ]
I have a Python `datetime` object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch. How do I do this?
``` >>> import datetime >>> # replace datetime.datetime.now() with your datetime object >>> int(datetime.datetime.now().strftime("%s")) * 1000 1312908481000 ``` Or the help of the time module (and without date formatting): ``` >>> import datetime, time >>> # replace datetime.datetime.now() with your datetime object ...
How can I convert a datetime object to milliseconds since epoch (unix time) in Python?
6,999,726
163
2011-08-09T16:43:08Z
11,111,177
228
2012-06-20T00:07:44Z
[ "python", "datetime", "epoch" ]
I have a Python `datetime` object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch. How do I do this?
It appears to me that the simplest way to do this is ``` import datetime epoch = datetime.datetime.utcfromtimestamp(0) def unix_time_millis(dt): return (dt - epoch).total_seconds() * 1000.0 ```
How can I convert a datetime object to milliseconds since epoch (unix time) in Python?
6,999,726
163
2011-08-09T16:43:08Z
14,583,130
7
2013-01-29T12:40:40Z
[ "python", "datetime", "epoch" ]
I have a Python `datetime` object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch. How do I do this?
This is how I do it: ``` from datetime import datetime from time import mktime dt = datetime.now() sec_since_epoch = mktime(dt.timetuple()) + dt.microsecond/1000000.0 millis_since_epoch = sec_since_epoch * 1000 ```
How can I convert a datetime object to milliseconds since epoch (unix time) in Python?
6,999,726
163
2011-08-09T16:43:08Z
16,501,740
13
2013-05-11T21:07:50Z
[ "python", "datetime", "epoch" ]
I have a Python `datetime` object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch. How do I do this?
You can use Delorean to travel in space and time! ``` import datetime import delorean dt = datetime.datetime.utcnow() delorean.Delorean(dt, timezone="UTC").epoch ``` <http://delorean.readthedocs.org/en/latest/quickstart.html>
How can I convert a datetime object to milliseconds since epoch (unix time) in Python?
6,999,726
163
2011-08-09T16:43:08Z
23,004,143
17
2014-04-11T05:23:37Z
[ "python", "datetime", "epoch" ]
I have a Python `datetime` object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch. How do I do this?
In Python 3.3, add new method. ``` datetime.timestamp() ``` <https://docs.python.org/3.3/library/datetime.html#datetime.datetime.timestamp>
Python: Is there a good way to check if text is encrypted?
7,000,885
4
2011-08-09T18:19:16Z
7,000,997
8
2011-08-09T18:26:55Z
[ "python", "encryption", "chat", "stream-cipher" ]
I've been playing around with [cryptocat](http://www.crypto.cat), which is an interesting online chat service that allows you to encrypt your messages with a key, so that only people with the same key can read your message. An interesting aspect of the service (in my opinion) is the fact that text encrypted using a key...
there is no guaranteed way to tell, but in practice you can do two things: 1. check for many non-ascii characters (if you're expecting people to be sending english text). 2. check the distribution of values. in normal text, some letters are much more common than others. but in encrypted text, all characters are about ...
How to remove white space at the bottom of matplotlib graph?
7,001,008
4
2011-08-09T18:27:57Z
7,006,380
8
2011-08-10T05:42:35Z
[ "python", "matplotlib" ]
I looked over the matplotlib user guide and cant seem to find a way to remove the white space that is generated at the bottom of my graph. ``` fig = plt.figure(1,figsize=(5,10)) axis = fig.add_subplot(211, autoscale_on=False,xlim=(1,10),ylim=(0,1)) ``` Are the configurations I am using on the graph. I tried using fra...
You're creating space for a second plot and not using it. The line ``` axis = fig.add_subplot(211, autoscale_on=False,xlim=(1,10),ylim=(0,1)) ``` adds a subplot to the figure, but the `211` means "two plots high by one plot wide, position 1". You could add a second plot below your current one with another subplot cal...
range over character in python
7,001,144
36
2011-08-09T18:37:45Z
7,001,205
21
2011-08-09T18:40:31Z
[ "python", "range", "character" ]
Is there an way to range over characters? something like this. ``` for c in xrange( 'a', 'z' ): print c ``` I hope you guys can help.
You have to convert the characters to numbers and back again. ``` for c in xrange(ord('a'), ord('z')+1): print chr(c) # resp. print unicode(c) ``` For the sake of beauty and readability, you can wrap this in a generator: ``` def character_range(a, b, inclusive=False): back = chr if isinstance(a,unicode) ...
range over character in python
7,001,144
36
2011-08-09T18:37:45Z
7,001,325
36
2011-08-09T18:49:51Z
[ "python", "range", "character" ]
Is there an way to range over characters? something like this. ``` for c in xrange( 'a', 'z' ): print c ``` I hope you guys can help.
``` import string for char in string.ascii_lowercase: print char ``` See [string constants](http://docs.python.org/library/string.html#string-constants) for the other possibilities, including uppercase, numbers, locale-dependent characters, all of which you can join together like `string.ascii_uppercase + string.a...
range over character in python
7,001,144
36
2011-08-09T18:37:45Z
7,001,371
56
2011-08-09T18:52:49Z
[ "python", "range", "character" ]
Is there an way to range over characters? something like this. ``` for c in xrange( 'a', 'z' ): print c ``` I hope you guys can help.
This is a great use for a custom generator: ``` def char_range(c1, c2): """Generates the characters from `c1` to `c2`, inclusive.""" for c in xrange(ord(c1), ord(c2)+1): yield chr(c) ``` then: ``` for c in char_range('a', 'z'): print c ```
range over character in python
7,001,144
36
2011-08-09T18:37:45Z
7,001,792
9
2011-08-09T19:27:10Z
[ "python", "range", "character" ]
Is there an way to range over characters? something like this. ``` for c in xrange( 'a', 'z' ): print c ``` I hope you guys can help.
There are other good answers here (personally I'd probably use string.lowercase), but for the sake of completeness, you could use [map()](http://docs.python.org/library/functions.html#map) and [chr()](http://docs.python.org/library/functions.html#chr) on the lower case ascii values: ``` for c in map(chr, xrange(97, 12...
json serialize a dictionary with tuples as key
7,001,606
19
2011-08-09T19:11:54Z
7,001,667
14
2011-08-09T19:16:47Z
[ "python", "json" ]
Is there a way in Python to serialize a dictionary that is using a tuple as key: ``` a={(1,2):'a'} ``` simply using json.dumps(a), produces: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/json/__init__.py", line 230, in dumps return _default_encoder.encode...
You can't serialize that as json, json has a much less flexible idea about what counts as a dict key than python. You could transform the mapping into a sequence of key, value pairs, something like this: ``` >>> import json >>> def remap_keys(mapping): ... return [{'key':k, 'value': v} for k, v in mapping.iterite...
TypeError: cannot concatenate 'str' and 'int' objects
7,001,664
4
2011-08-09T19:16:40Z
7,001,679
9
2011-08-09T19:17:59Z
[ "python", "string", "integer", "concatenation", "typeerror" ]
I'm learning Python now, yay! Anyway, I have small problem. I don't see problem in here: ``` x = 3 y = 7 z = 2 print "I told to the Python, that the first variable is %d!" % x print "Anyway, 2nd and 3rd variables sum is %d. :)" % y + z ``` But Python thinks different - `TypeError: cannot concatenate 'str' and 'int' ...
You need to put parenthesis: `(y+z)`
TypeError: cannot concatenate 'str' and 'int' objects
7,001,664
4
2011-08-09T19:16:40Z
7,001,736
12
2011-08-09T19:23:05Z
[ "python", "string", "integer", "concatenation", "typeerror" ]
I'm learning Python now, yay! Anyway, I have small problem. I don't see problem in here: ``` x = 3 y = 7 z = 2 print "I told to the Python, that the first variable is %d!" % x print "Anyway, 2nd and 3rd variables sum is %d. :)" % y + z ``` But Python thinks different - `TypeError: cannot concatenate 'str' and 'int' ...
`%` has a higher precedence than `+`, so `s % y + z` is parsed as `(s % y) + z`. If `s` is a string, then `s % x` is a string, and `(s % y) + z` attempts to add a string (the result of `s % y`) and an integer (the value of `z`).
Pause Python Generator
7,001,917
3
2011-08-09T19:36:40Z
7,001,949
8
2011-08-09T19:39:52Z
[ "python", "generator" ]
I have a python generator that does work that produces a large amount of data, which uses up a lot of ram. Is there a way of detecting if the processed data has been "consumed" by the code which is using the generator, and if so, pause until it is consumed? ``` def multi_grab(urls,proxy=None,ref=None,xpath=False,compr...
A generator simply yields values. There's no way for the generator to know what's being done with them. But the generator also pauses constantly, as the caller does whatever it does. It doesn't execute again until the caller invokes it to get the next value. It doesn't run on a separate thread or anything. It sounds l...
Help choosing between Django, Zope3 and Web2Py for WebService Server
7,001,931
2
2011-08-09T19:37:54Z
7,002,398
8
2011-08-09T20:18:42Z
[ "python", "django", "web-services", "web2py", "zope3" ]
I need to build a simple administrative webapp using python that will connect to MySQL. Web Application will need to expose some APIs via Web Services for other Web App and Android/iPhone clients to consume. I need help making technology selections. I would appreciate suggestions and past experience comment compariso...
Don't even consider using SOAP. Design a RESTful API, support JSON and XML. You could accomplish this with pretty much any Python web framework. If you use Django there are numerous apps out there for accomplishing this, I like [Tastypie](http://django-tastypie.readthedocs.org/en/latest/).
expected buffer object error on string.translate - python 2.6
7,002,206
3
2011-08-09T20:01:25Z
7,002,253
7
2011-08-09T20:04:58Z
[ "python", "string", "translate" ]
I´d appreciate some help for a python novice, I´m trying to delete some characters from a string, like this, for example: ``` string1 = "100.000" deleteList = [",", "."] string1.translate(None, deleteList) print string1 ``` but I get a `TypeError: expected a character buffer object` Why do I get this error, whic...
The [docs for `string.translate`](http://docs.python.org/library/string.html#string.translate) says ``` S.translate(table [,deletechars]) -> string ``` which suggests that `deletechars` should be a string of characters, instead of a list of characters: ``` string1 = "100.000" string1=string1.translate(None, ',.') pr...
How can I extract all values from a dictionary in Python?
7,002,429
65
2011-08-09T20:22:14Z
7,002,449
129
2011-08-09T20:23:55Z
[ "python", "dictionary", "extract" ]
I have a dictionary `d = {1:-0.3246, 2:-0.9185, 3:-3985, ...}`. How do I extract all of the values of `d` into a list `l`?
If you only need the dictionary keys `1`, `2`, and `3` use: `your_dict.keys()`. If you only need the dictionary values `-0.3246`, `-0.9185`, and `-3985` use: `your_dict.values()`. If you want both keys and values use: `your_dict.items()` which returns a list of tuples `[(key1, value1), (key2, value2), ...]`.
How can I extract all values from a dictionary in Python?
7,002,429
65
2011-08-09T20:22:14Z
7,002,450
7
2011-08-09T20:23:56Z
[ "python", "dictionary", "extract" ]
I have a dictionary `d = {1:-0.3246, 2:-0.9185, 3:-3985, ...}`. How do I extract all of the values of `d` into a list `l`?
Use `values()` ``` >>> d = {1:-0.3246, 2:-0.9185, 3:-3985} >>> d.values() <<< [-0.3246, -0.9185, -3985] ```
Python logging exception
7,003,034
17
2011-08-09T21:09:34Z
7,003,107
22
2011-08-09T21:16:22Z
[ "python", "exception", "logging", "design-patterns" ]
I'm currently writing a wrapper class. I want to be able to log exceptions properly but allow calling methods to be aware of exceptions which occur. My class looks like this: ``` import logging log = logging.getLogger('module') class MyAPIWrapper(library.APIClass): def __init__(self): self.log = logging...
There is nothing wrong with catching to log. However, I'd recommend: ``` try: response = self.call_api_method() except APIException, e: # or 'as e' depending on your Python version self.log.exception('Oh noes!') raise #Throw exception again so calling code knows it happened else: ...
Using functools.wraps with a logging decorator
7,003,898
13
2011-08-09T22:39:08Z
7,004,565
9
2011-08-10T00:15:03Z
[ "python", "logging" ]
I'm trying to write a simple decorator that logs a given statement before calling the decorated function. The logged statements should both appear to come from the same function, which I thought was the purpose of functools.wraps(). Why does the following code: ``` import logging logging.basicConfig( level=loggin...
Unfortunately `logging` uses the function code object to infer the name. You could work around this by using the [`extra`](http://docs.python.org/library/logging.html#logging.Logger.debug) keyword argument to specify some additional attributes for the record, which you could then use during formatting. You could do som...
Extracting contents of a string within parentheses
7,004,868
2
2011-08-10T01:12:42Z
7,005,009
7
2011-08-10T01:39:37Z
[ "python" ]
I have the following string: ``` string = "Will Ferrell (Nick Halsey), Rebecca Hall (Samantha), Michael Pena (Frank Garcia)" ``` I would like to create a list of tuples in the form of `[(actor_name, character_name),...]` like so: ``` [(Will Ferrell, Nick Halsey), (Rebecca Hall, Samantha), (Michael Pena, Frank Garcia...
``` string = "Will Ferrell (Nick Halsey), Rebecca Hall (Samantha), Michael Pena (Frank Garcia)" import re pat = re.compile(r'([^(]+)\s*\(([^)]+)\)\s*(?:,\s*|$)') lst = [(t[0].strip(), t[1].strip()) for t in pat.findall(string)] ``` The compiled pattern is a bit tricky. It's a raw string, to make the backslashes less...
Using unitialized variables in Python
7,005,072
3
2011-08-10T01:53:17Z
7,005,116
11
2011-08-10T02:00:56Z
[ "python", "initialization", "pylint" ]
Background: I have a class modeling a chip with registers, the chip has a bunch of registers, one of them is a high temperature limit for the built-in temperature sensor. I have the following: ``` class foo(): def __init__(self): # does not set self._hiTemp! ... def setHiTemp(self, t): self._hiTemp = ...
The way I'd do it is set it to `None` or some other sentinel value that doesn't occur 'in nature'. Then for operations that require it to be set, use an `assert` to fail fast in case the caller is trying to use your object inappropriately. ``` def __init__(self): self._hiTemp = None def checkHiTemp(self): ass...
Simple idiom to break an n-long list into k-long chunks, when n % k > 0?
7,005,323
12
2011-08-10T02:44:54Z
7,005,407
15
2011-08-10T03:01:17Z
[ "python", "itertools", "map-function" ]
In Python, it is easy to break an *n*-long list into *k*-size chunks if *n* is a multiple of *k* (IOW, `n % k == 0`). Here's my favorite approach (straight from the [**docs**](http://docs.python.org/library/functions.html#zip)): ``` >>> k = 3 >>> n = 5 * k >>> x = range(k * 5) >>> zip(*[iter(x)] * k) [(0, 1, 2), (3, 4...
``` [x[i:i+k] for i in range(0,n,k)] ```
How do I hide the console when I use os.system() or subprocess.call()?
7,006,238
27
2011-08-10T05:21:10Z
7,006,424
43
2011-08-10T05:48:26Z
[ "python", "windows", "console" ]
I wrote some statements like below: ``` os.system(cmd) #do something subprocess.call('taskkill /F /IM exename.exe') ``` both will pop up a console. How can I stop it from popping up the console?
The process `STARTUPINFO` can hide the console window: ``` si = subprocess.STARTUPINFO() si.dwFlags |= subprocess.STARTF_USESHOWWINDOW #si.wShowWindow = subprocess.SW_HIDE # default subprocess.call('taskkill /F /IM exename.exe', startupinfo=si) ``` Or set the creation flags to disable creating the window: ``` CREATE...
How do I hide the console when I use os.system() or subprocess.call()?
7,006,238
27
2011-08-10T05:21:10Z
7,509,054
11
2011-09-22T02:55:47Z
[ "python", "windows", "console" ]
I wrote some statements like below: ``` os.system(cmd) #do something subprocess.call('taskkill /F /IM exename.exe') ``` both will pop up a console. How can I stop it from popping up the console?
Add the `shell=True` argument to the subprocess calls. ``` subprocess.call('taskkill /F /IM exename.exe', shell=True) ``` Or, if you don't need to wait for it, use `subprocess.Popen` rather than `subprocess.call`. ``` subprocess.Popen('taskkill /F /IM exename.exe', shell=True) ```
How to calculate expression using sympy in python
7,006,626
14
2011-08-10T06:18:26Z
7,006,736
17
2011-08-10T06:32:16Z
[ "python", "expression", "sympy" ]
I need a calculate below expression using sympy in python? ``` exp = '(a+b)*40-(c-a)/0.5' ``` In `a=6`, `b=5`, `c=2` this case how to calculate expression using sympy in python? Please help me.
The documentation is here: <http://docs.sympy.org/>. You should really read it! To "calculate" your expression, write something like this: ``` from sympy import Symbol a = Symbol("a") b = Symbol("b") c = Symbol("c") exp = (a+b)*40-(c-a)/0.5 ``` And that's it. If you meant something else by "calculate", you could als...
How to calculate expression using sympy in python
7,006,626
14
2011-08-10T06:18:26Z
13,225,555
8
2012-11-05T03:28:37Z
[ "python", "expression", "sympy" ]
I need a calculate below expression using sympy in python? ``` exp = '(a+b)*40-(c-a)/0.5' ``` In `a=6`, `b=5`, `c=2` this case how to calculate expression using sympy in python? Please help me.
You can convert your string into a sympy expression using [the `parse_expr()` function in the module `sympy.parsing.sympy_parser`](http://docs.sympy.org/0.7.2/modules/parsing.html#sympy.parsing.sympy_parser.parse_expr). ``` >>> from sympy.abc import a, b, c >>> from sympy.parsing.sympy_parser import parse_expr >>> sym...
Alternative to list comprehension if there will be only one result
7,006,839
31
2011-08-10T06:43:15Z
7,006,873
43
2011-08-10T06:47:17Z
[ "python", "list-comprehension" ]
I'm starting to get used to list comprehension in Python but I'm afraid I'm using it somewhat improperly. I've run into a scenario a few times where I'm using list comprehension but immediately taking the first (and only) item from the list that is generated. Here is an example: ``` actor = [actor for actor in self.ac...
You could use a generator expression and `next` instead. This would be more efficient as well, since an intermediate list is not created and iteration can stop once a match has been found: ``` actor = next(actor for actor in self.actors if actor.name==actorName) ``` And as [senderle](http://stackoverflow.com/users/57...
Alternative to list comprehension if there will be only one result
7,006,839
31
2011-08-10T06:43:15Z
7,008,062
12
2011-08-10T08:45:29Z
[ "python", "list-comprehension" ]
I'm starting to get used to list comprehension in Python but I'm afraid I'm using it somewhat improperly. I've run into a scenario a few times where I'm using list comprehension but immediately taking the first (and only) item from the list that is generated. Here is an example: ``` actor = [actor for actor in self.ac...
If you want to take the first match of potentially many, `next(...)` is great. But if you expect exactly one, consider writing it defensively: ``` [actor] = [actor for actor in self.actors if actor.name==actorName] ``` This always scans to the end, but unlike `[0]`, the destructuring into `[actor]` throws a ValueErro...
Query when parameter is none django
7,006,862
5
2011-08-10T06:45:20Z
7,006,919
7
2011-08-10T06:53:27Z
[ "python", "mysql", "django", "django-models" ]
I want to make a query, something like ``` Model.objects.filter(x=x).filter(y=y).filter(z=z) ``` ... but there are some cases when for example y is None. This literally searches the database for null values in the y column -- is there a nifty way to essentially disregard that query parameter if it is none, i.e. retur...
I do not know, if I get your question, but ``` Model.objects.filter(x=x, y__isnull = False, z=z) ``` gives you the queryset, where the `y`column is non-null (`IS NOT NULL`). [Here's](https://docs.djangoproject.com/en/1.3/ref/models/querysets/#isnull) the relevant documentation. EDIT: Check if y is None and build yo...
os.path equivalent for web urls in python?
7,007,496
9
2011-08-10T07:52:11Z
7,007,552
12
2011-08-10T07:57:16Z
[ "python", "url", "path" ]
For joining, splitting and processing file and directory paths python's `os.path` modul is great. Is there an equivalent for web urls?
[**urlparse**](http://docs.python.org/library/urlparse.html) - Parse URLs into components, is the module for you.. To actually fetch urls & data, you need [**urllib2**](http://docs.python.org/library/urllib2.html).
Python: Getting files into an archive without the directory?
7,007,868
10
2011-08-10T08:27:59Z
7,008,439
13
2011-08-10T09:16:53Z
[ "python", "zipfile" ]
I've been learning python for about 3 weeks now, and I'm currently trying to write a little script for sorting files (about 10.000) by keywords and date appearing in the filename. Files before a given date should be added to an archive. The sorting works fine, but not the archiving It creates an archive - the name is ...
From help(zipfile): ``` | write(self, filename, arcname=None, compress_type=None) | Put the bytes from filename into the archive under the name | arcname. ``` So try changing your write() call with: ``` x.write(folder + '/' + item + '/' + f, arcname = f) ``` About your code, it seems to me good enough...
scipy.io.loadmat nested structures (i.e. dictionaries)
7,008,608
17
2011-08-10T09:32:08Z
8,832,212
22
2012-01-12T08:47:03Z
[ "python", "nested", "structure", "scipy", "dictionary" ]
Using the given routines (how to load Matlab .mat files with scipy), I could not access deeper nested structures to recover them into dictionaries To present the problem I run into in more detail, I give the following toy example: ``` load scipy.io as spio a = {'b':{'c':{'d': 3}}} # my dictionary: a['b']['c']['d'] = ...
Here are the functions, which reconstructs the dictionaries just use this loadmat instead of scipy.io's loadmat: ``` import scipy.io as spio def loadmat(filename): ''' this function should be called instead of direct spio.loadmat as it cures the problem of not properly recovering python dictionaries f...
Django - redirect to version with www
7,009,884
6
2011-08-10T11:15:08Z
11,363,914
11
2012-07-06T14:13:19Z
[ "python", "django", "redirect", "dns" ]
Is in Django a simple way to redirect everything from domain without www to version with it? I mean from http:// example.com to http:// www.example.com.
I have it. It is PREPEND\_WWW in settings. <https://docs.djangoproject.com/en/dev/ref/settings/?from=olddocs#prepend-www>
django staticfiles with multiple apps
7,011,041
4
2011-08-10T12:50:41Z
7,011,392
8
2011-08-10T13:17:48Z
[ "python", "django" ]
Let's say I have two apps: foo and bar the project structure like below, how do I make sure app styles do not conflict? Running manage.py collectstatic dissolves either one of the files currently... The admin app is imported to the collected directory within an 'admin' folder however my app static data gets imported ...
Don't do that this way. With or without staticfiles/collectstatic, djando would ever serve one of the two `style.css` files. Just prepend the app name inside `static/`. See also how `django/contrib/(admin|auth|...)/static` are laid out ``` Project |-- foo | |-- static | | `-- foo | | `-- css | | ...
how to get a single result from a SQLite query in python?
7,011,291
17
2011-08-10T13:09:07Z
7,011,319
34
2011-08-10T13:11:58Z
[ "python", "sql", "sqlite" ]
Is there an elegant way of getting a single result from an SQLite SELECT query when using python 2.7? for example: ``` conn = sqlite3.connect('db_path.db') cursor=conn.cursor() cursor.execute("SELECT MAX(value) FROM table") for row in cursor: for elem in row: maxVal = elem ``` is there a way to avoid th...
i think you're looking for [Cursor.fetchone()](http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.fetchone) : ``` cursor.fetchone()[0] ```
getting elements in a list according to list of indices in python
7,011,636
2
2011-08-10T13:34:01Z
7,011,673
8
2011-08-10T13:36:21Z
[ "python" ]
I have a list of indices, something like: ``` b=[0,2] ``` and a list of elements: ``` a = ['elem0','elem1','elem2'] ``` I need a list that is composed of the elements in `a` with the indices in `b` (in this example: `['elem0','elem2']`)
Use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` [a[i] for i in b] ```
Python - how to change email text typeface
7,011,992
4
2011-08-10T13:58:04Z
7,012,048
7
2011-08-10T14:01:46Z
[ "python", "email" ]
I'm writing an app that generates full report and it's summary, and sends them via email. A summary is sent as text in email, and a full report is sent as attachement. I found an example ([link](http://snippets.dzone.com/posts/show/757)) that works great, but I would need to set font's typeface of an email message as m...
Email will send as both plaintext and as HTML. A plaintext email renderer will generally be rendered in a monospace font, but there is no guarantee of that. More importantly, there is nothing you can do to change what font the plaintext will display in. If your recipient is reading mail in an HTML capable email client...
How to write a call back function for ignore in shutil.copytree
7,012,686
7
2011-08-10T14:43:38Z
7,012,866
7
2011-08-10T14:54:47Z
[ "python", "file-copying", "shutil" ]
I am relatively new to python. I am trying to copy a directory to another directory maintaining the structure. I am using ``` shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False) ``` I am trying to write a call back function for ignore. My aim is to ta...
The return of the ignore function needs to be a list of directories and files to ignore. You aren't returning anything, which returns `None`, so you are getting the error `TypeError: argument of type 'NoneType' is not iterable`. Here's an example that will copy the folder structure and the files listed in 'copy\_these...
Assignment statement value
7,012,742
16
2011-08-10T14:46:45Z
7,012,788
24
2011-08-10T14:49:41Z
[ "python", "variable-assignment" ]
Everybody knows that in Python assignments do not return a value, presumably to avoid assignments on `if` statements when usually just a comparison is intended: ``` >>> if a = b: File "<stdin>", line 1 if a = b: ^ SyntaxError: invalid syntax >>> if a == b: ... pass ... ``` For the same reason, one...
It's right there in the syntax: ``` assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression) ``` The tiny `+` at the end of `(target_list "=")+` means "one or more". So the line `a = b = c = 2` does not consist of 3 assignment statements, but of *a single assignment statement* with 3 target lists....
Turn off caching of static files in Django development server
7,013,735
14
2011-08-10T15:47:03Z
7,015,940
16
2011-08-10T18:36:00Z
[ "python", "django" ]
**Is there an easy way to turn off caching of static files in Django's development server?** I'm starting the server with the standard command: ``` $ python manage.py runserver ``` I've got `settings.py` configured to serve up static files from the `/static` directory of my Django project. I've also got a middleware...
@Erik Forsberg's answer worked for me. Here's what I had to do: * Comment out the staticfiles app from `INSTALLED_APPS` in `settings.py`: ``` INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.me...
Turn off caching of static files in Django development server
7,013,735
14
2011-08-10T15:47:03Z
11,369,944
8
2012-07-06T21:34:50Z
[ "python", "django" ]
**Is there an easy way to turn off caching of static files in Django's development server?** I'm starting the server with the standard command: ``` $ python manage.py runserver ``` I've got `settings.py` configured to serve up static files from the `/static` directory of my Django project. I've also got a middleware...
My very simple solution: ``` from django.contrib.staticfiles.views import serve from django.views.decorators.cache import never_cache static_view = never_cache(serve) urlpatterns += static_view(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ```
Turn off caching of static files in Django development server
7,013,735
14
2011-08-10T15:47:03Z
18,162,302
9
2013-08-10T13:19:56Z
[ "python", "django" ]
**Is there an easy way to turn off caching of static files in Django's development server?** I'm starting the server with the standard command: ``` $ python manage.py runserver ``` I've got `settings.py` configured to serve up static files from the `/static` directory of my Django project. I've also got a middleware...
Django's `contrib.staticfiles` app automatically serves staticfiles for you by overriding the `runserver` command. With this configuration you can't control the way it serves the static files. You can prevent the staticfiles app from serving the static files by adding the `--nostatic` option to the runserver command: ...
Getting python to print in UTF8 on Windows XP with the console
7,014,430
11
2011-08-10T16:34:19Z
7,018,164
8
2011-08-10T21:36:53Z
[ "python", "windows", "unicode", "utf-8", "windows-xp" ]
I would like to configure my console on Windows XP to support UTF8 and to have python detect that and work with it. So far, my attempts: ``` C:\Documents and Settings\Philippe>C:\Python25\python.exe Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credit...
> I would like to configure my console on Windows XP to support UTF8 I don't think it's going to happen. The 65001 code page is buggy; some stdio calls behave incorrectly and break many tools. Whilst you can register cp65001 as an encoding manually: ``` def cp65001(name): if name.lower()=='cp65001': retu...
In Python, how do I remove from a list any element containing certain kinds of characters?
7,014,674
9
2011-08-10T16:52:28Z
7,014,963
15
2011-08-10T17:13:47Z
[ "python", "regex", "list", "elements" ]
Apologies if this is a simple question, I'm still pretty new to this, but I've spent a while looking for an answer and haven't found anything. I have a list that looks something like this horrifying mess: ``` ['Organization name} ', '> (777) 777-7777} ', ' class="lsn-mB6 adr">1 Address, MA 02114 } ', ' class="lsn-serp...
I think your regex is incorrect, to match all entries that contain all-cap words with three or more characters, you should use something like this with `re.search`: ``` regex = re.compile(r'\b[A-Z]{3,}\b') ``` With that you can filter using a list comprehension or the `filter` built-in function: ``` full = ['Organiz...
I need to securely store a username and password in Python, what are my options?
7,014,953
26
2011-08-10T17:13:04Z
7,015,578
9
2011-08-10T18:03:51Z
[ "python", "security", "encryption" ]
I'm writing a small Python script which will periodically pull information from a 3rd party service using a username and password combo. I don't need to create something that is 100% bulletproof (does 100% even exist?), but I would like to involve a good measure of security so at the very least it would take a long tim...
I recommend a strategy similar to [ssh-agent](http://en.wikipedia.org/wiki/Ssh-agent). If you can't use ssh-agent directly you could implement something like it, so that your password is only kept in RAM. The cron job could have configured credentials to get the actual password from the agent each time it runs, use it ...
I need to securely store a username and password in Python, what are my options?
7,014,953
26
2011-08-10T17:13:04Z
14,493,675
10
2013-01-24T03:54:17Z
[ "python", "security", "encryption" ]
I'm writing a small Python script which will periodically pull information from a 3rd party service using a username and password combo. I don't need to create something that is 100% bulletproof (does 100% even exist?), but I would like to involve a good measure of security so at the very least it would take a long tim...
After looking though the answers to this and related questions, I've put together some code using a few of the suggested methods for encrypting and obscuring secret data. This code is specifically for when the script has to run without user intervention (if the user starts it manually, it's best to have them put in the...
Edit jar files with python
7,015,203
6
2011-08-10T17:34:22Z
7,015,233
10
2011-08-10T17:36:18Z
[ "java", "python", "jar" ]
Do you know a python module with which i can add files to a JAR archive? (what i wan't to do is add .class files to a jar archive) and the program that has to do it has to be written in python Thanks!
.jar files are just .zip files with a different file extension and a manifest. Try <http://docs.python.org/library/zipfile.html>
map(function, sequence) where function returns two values
7,015,307
4
2011-08-10T17:42:58Z
7,015,387
8
2011-08-10T17:48:36Z
[ "python" ]
Look at the following Python code: ``` def function(x): return x, x+1 sequence = range(5) map(function, sequence) ``` this returns ``` [(0,1), (1,2), (2,3), (3,4), (4,5)] ``` I want to get the output ``` [0, 1, 2, 3, 4], [1, 2, 3, 4, 5] ``` That means, I want to get the two outputs of function into two diff...
Hope this helps: ``` >>> a = [(0,1), (1,2), (2,3), (3,4), (4,5)] >>> zip(*a) [(0, 1, 2, 3, 4), (1, 2, 3, 4, 5)] ``` <http://docs.python.org/library/functions.html#zip>
ctypes variable length structures
7,015,487
11
2011-08-10T17:55:28Z
7,016,078
9
2011-08-10T18:46:56Z
[ "python", "python-3.x", "ctypes" ]
Ever since I read Dave Beazley's post on binary I/O handling (http://dabeaz.blogspot.com/2009/08/python-binary-io-handling.html) I've wanted to create a Python library for a certain wire protocol. However, I can't find the best solution for variable length structures. Here's what I want to do: ``` import ctypes as c ...
The most straightforward way, with the example you gave is to define the structure just when you have the information you need. A simple way of doing that is creating the class at the point you will use it, not at module root - you can, for example, just put the `class` body inside a function, that will act as a facto...
django and backbone.js questions
7,015,638
23
2011-08-10T18:09:27Z
7,017,600
21
2011-08-10T20:49:45Z
[ "javascript", "python", "django", "backbone.js" ]
I'm looking at making backbone.js (plus jQuery) work with my django app, but I have some questions. I've never used a restful setup before, so I have very little knowledge of the "proper" way to use REST. 1. Backbone uses REST architecture, but django doesn't support this by default. It looks like tastypie or piston a...
you can point backbone collections/models toward whatever urls you want and parse the response however you want in your backbone "subclasses". Model.url: <http://documentcloud.github.com/backbone/docs/backbone.html#section-43> Collection.parse: <http://documentcloud.github.com/backbone/docs/backbone.html#section-69...
Python logging not outputting anything
7,016,056
19
2011-08-10T18:45:29Z
7,016,398
30
2011-08-10T19:12:29Z
[ "python", "logging" ]
In a python script I am writing, I am trying to log events using the logging module. I have the following code to configure my logger: ``` ERROR_FORMAT = "%(levelname)s at %(asctime)s in %(funcName)s in %(filename) at line %(lineno)d: %(message)s" DEBUG_FORMAT = "%(lineno)d in %(filename)s at %(asctime)s: %(message)s"...
The default logging level is warning. Since you haven't changed the level, the root logger's level is still warning. That means that it will ignore any logging with a level that is lower than warning, including debug loggings. This is explained in the [tutorial](http://docs.python.org/howto/logging.html#a-simple-examp...
PicklingError when using multiprocessing
7,016,567
22
2011-08-10T19:26:25Z
7,017,546
16
2011-08-10T20:44:17Z
[ "python", "multiprocessing" ]
I am having trouble when using the Pool.map\_async() (and also Pool.map()) in the multiprocessing module. I have implemented a parallel-for-loop function that works fine as long as the function input to Pool.map\_async is a "regular" function. When the function is e.g. a method to a class, then I get a PicklingError: ...
The problem here is less of the "pickle" error message than conceptual: multiprocess does fork your code in "worker" different processes in order to perform its magic. It then sends data to and from the different process by seamlessly serializing and de-serializing the data (that is the part that uses the pickle). Wh...
Why does python's dictionary iteration seemingly work with a copy?
7,016,696
6
2011-08-10T19:35:58Z
7,016,732
7
2011-08-10T19:38:35Z
[ "python", "iterator", "copy", "items" ]
I am confused how python is iterating through this dictionary. From python's documentation, the itervalues returns an iterator over the dictionary's values. ``` dict = {"hello" : "wonderful", "today is" : "sunny", "more text" : "is always good"} for x in dict.itervalues(): x = x[2:] print dict ``` This print...
This has nothing to do with strings or lists. The devil is in how the `for` is unfolded. Doing ``` for x in d.iteritems(): # loop body ``` is more-or-less equivalent to doing ``` iter = d.itervalues() while True: try: x = next(iter) # loop body except StopIteration: break ``` So...
Best way to deal with default params in Python?
7,017,414
8
2011-08-10T20:33:19Z
7,017,436
13
2011-08-10T20:35:35Z
[ "python" ]
I've got some code (that someone else wrote): ``` def render(self, name, value, attrs=None): if not attrs: attrs = {} attrs.update({'class': 'ui-autocomplete-input'}) ``` which I think could be re-written as: ``` def render(self, name, value, attrs={}): attrs.update({'class': 'ui-autocomplete-inp...
Using `attrs = {}` in the function signature will bite you, since it will keep its value on successive calls to the function. The original code is best. eg. ``` >>> def a(attrs= {}): ... print attrs ... attrs.update({1:1}) ... >>> a() {} >>> a() {1: 1} ``` Note how it kept the value assigned the first time, on t...
Interesting "Hello World" Interview
7,017,874
8
2011-08-10T21:11:53Z
7,017,909
13
2011-08-10T21:15:08Z
[ "python" ]
We have a question we ask at our office during interviews that goes like this. For the sake of consistency, I am restricting the context of this to python. I'm sure there are other answers but I'm really only interested in python answers. Write me a function named `say` that when called like this: ``` >>> say('Hello'...
**Python 2.x answers** The obvious answer that doesn't actually count because it returns the string instead of printing it: ``` >>> say = lambda x: lambda y: x + " " + y >>> say('Hello')('World') 'Hello World' ``` This one is 45 characters counting newlines: ``` def p(x): print "Hello World" say=lambda x:p ``` Th...
Get variables from a settings.py file in a Jinja template with Flask
7,017,990
8
2011-08-10T21:20:49Z
7,027,035
14
2011-08-11T13:49:26Z
[ "python", "flask", "jinja2" ]
Say I have settings.py file with a bunch of constants (maybe more, in the future). How do I access those variables in a Jinja template?
Flask automatically includes your application's config in the [standard context](http://flask.pocoo.org/docs/templating/#standard-context). So if you used `app.config.from_envvar` or `app.config.from_pyfile` to pull in the values from your settings file, you already have access to those values in your Jinja templates (...
Running quick if statements in Django template language
7,018,005
13
2011-08-10T21:22:20Z
7,018,133
26
2011-08-10T21:33:55Z
[ "python", "django", "if-statement", "django-templates" ]
I'm using this code: ``` <div class="stream {% if streams.online %}online{% else %}offline{% endif %}"> ``` It seems a little redundant. I'd love to run this code ``` <div class="stream {{ 'online' if stream.online else 'offline' }}"> ``` But sadly that doesn't work. Is there a shorter and less messy way of doing w...
Can't you use the [`yesno` built-in template filter](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#yesno)? As in, ``` <div class="stream {{ stream.online|yesno:"online,offline" }}"> ```
PySerial: How to send Ctrl-C command on the serial line
7,018,139
9
2011-08-10T21:34:36Z
7,018,187
11
2011-08-10T21:39:01Z
[ "python", "serial-port", "copy-paste", "pyserial" ]
I'm automating a configuration process for an embedded board. To enter the setup screen I need to send "Ctrl-C" command. This is **NOT** to interrupt a process I'm running locally, **KeyboardInterrupt** will **not work**. I need to send a value that will be interpreted by the bootloader as Ctrl-C. What is the value I...
IIRC, Ctrl-C is `etx`. Thus send `\x03`.
Automatically Type Cast Parameters In Python
7,019,283
12
2011-08-10T23:42:10Z
7,019,382
8
2011-08-10T23:58:16Z
[ "python", "types", "parameters", "casting" ]
**Background:** I mostly run python scripts from the command line in pipelines and so my arguments are always strings that need to be type casted to the appropriate type. I make a lot of little scripts each day and type casting each parameter for every script takes more time than it should. **Question:** Is there ...
If you want to auto-convert values: ``` def boolify(s): if s == 'True': return True if s == 'False': return False raise ValueError("huh?") def autoconvert(s): for fn in (boolify, int, float): try: return fn(s) except ValueError: pass return s...
Overriding properties in python
7,019,643
26
2011-08-11T00:48:05Z
7,020,271
29
2011-08-11T02:46:38Z
[ "python", "inheritance", "properties", "override" ]
So, I'm trying to figure out the best (most elegant with the least amount of code) way to allow overriding specific functions of a property (e.g., just the getter, just the setter, etc.) in python. I'm a fan of the following way of doing properties, due to the fact that all of their methods are encapsulated in the same...
I'm sure you've heard this before, but `apply` has been deprecated **for eight years**, since Python 2.3. Don't use it. Your use of `locals()` is also contrary to the Zen of Python -- explicit is better than implicit. If you really like the increased indentation, there is no need to create a throwaway object, just do ...
Overriding properties in python
7,019,643
26
2011-08-11T00:48:05Z
7,020,531
27
2011-08-11T03:33:50Z
[ "python", "inheritance", "properties", "override" ]
So, I'm trying to figure out the best (most elegant with the least amount of code) way to allow overriding specific functions of a property (e.g., just the getter, just the setter, etc.) in python. I'm a fan of the following way of doing properties, due to the fact that all of their methods are encapsulated in the same...
The Python docs on the `property` decorator suggest the following idiom: ``` class C(object): def __init__(self): self._x = None @property def x(self): return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x ``` And t...
Python: for loop between if-else, how/why does this work?
7,019,794
5
2011-08-11T01:17:10Z
7,019,810
8
2011-08-11T01:20:20Z
[ "python", "conditional", "if-statement" ]
I'm currently going through the Lynda Python tutorial and in the section on generators I see the following code: ``` def isprime(n): if n == 1: return False for x in range(2, n): if n % x == 0: return False else: return True ``` I didn't catch it at first, but as I was ...
An `else:` block after a `for:` block only runs if the loop completed normally. If you `break` out of the loop, it won't run. In this case, this makes no difference because you never break out of the loop; you `return` before it ends or you let it complete normally.
What is 'print' in Python?
7,020,417
60
2011-08-11T03:12:23Z
7,020,426
62
2011-08-11T03:14:29Z
[ "python" ]
I understand what `print` does, but of what "type" is that language element? I think it's a function, but why does this fail? ``` >>> print print SyntaxError: invalid syntax ``` Isn't `print` a function? Shouldn't it print something like this? ``` >>> print print <function print at ...> ```
In 2.7 and down, `print` is a statement. In python 3, `print` is a function. To use the print function in Python 2.6 or 2.7, you can do ``` >>> from __future__ import print_function >>> print(print) <built-in function print> ``` See [this section](http://docs.python.org/reference/simple_stmts.html#grammar-token-print...
What is 'print' in Python?
7,020,417
60
2011-08-11T03:12:23Z
7,020,488
21
2011-08-11T03:25:20Z
[ "python" ]
I understand what `print` does, but of what "type" is that language element? I think it's a function, but why does this fail? ``` >>> print print SyntaxError: invalid syntax ``` Isn't `print` a function? Shouldn't it print something like this? ``` >>> print print <function print at ...> ```
`print` is a mistake that has been rectified in Python 3. In Python 3 it is a function. In Python 1.x and 2.x it is not a function, it is a special form like `if` or `while`, but unlike those two it is not a control structure. So, I guess the most accurate thing to call it is a statement.
What is 'print' in Python?
7,020,417
60
2011-08-11T03:12:23Z
7,020,500
7
2011-08-11T03:29:06Z
[ "python" ]
I understand what `print` does, but of what "type" is that language element? I think it's a function, but why does this fail? ``` >>> print print SyntaxError: invalid syntax ``` Isn't `print` a function? Shouldn't it print something like this? ``` >>> print print <function print at ...> ```
In Python all statements (except assignment) are expressed with reserved words, not addressible objects. That is why you cannot simply `print print` and you get a `SyntaxError` for trying. It's a reserved word, not an object. Confusingly, you **can** have a variable named `print`. You can't address it in the normal wa...
What is 'print' in Python?
7,020,417
60
2011-08-11T03:12:23Z
7,020,524
34
2011-08-11T03:33:05Z
[ "python" ]
I understand what `print` does, but of what "type" is that language element? I think it's a function, but why does this fail? ``` >>> print print SyntaxError: invalid syntax ``` Isn't `print` a function? Shouldn't it print something like this? ``` >>> print print <function print at ...> ```
In Python 3, [`print()`](http://docs.python.org/release/3.1.3/library/functions.html#print) is a built-in function (object) Before this, [`print`](http://www.python.org/doc//current/reference/simple_stmts.html#the-print-statement) was a *statement*. Demonstration... # Python 2.*x*: ``` % pydoc2.6 print The ``print`...
Drawing & Rendering Multiway Tree in Python
7,020,741
9
2011-08-11T04:11:40Z
7,021,083
14
2011-08-11T05:11:11Z
[ "python", "graph", "tree", "graphviz", "multiway-tree" ]
Does somebody know how do I plot a multiway-tree in a aesthetically plausible way? info: * more or less 100 items * each level have approximately the same number of items * 10 levels * each node have between 0(leaf) and 6 childs * each node specify it's own level, no matter his roots. I'm currently using PIL, dividin...
So, rendering graphs is the particular genius of [graphviz](http://www.graphviz.org/), which also happens to have several libraries that provide python bindings. In my opinion, the best of these bindings libraries is [pygraphviz](http://networkx.lanl.gov/pygraphviz/). Graphviz is probably the best solution and also lik...
Unittest setUpClass not working
7,020,781
4
2011-08-11T04:19:04Z
8,100,067
8
2011-11-11T21:15:10Z
[ "python", "unit-testing", "python-3.x" ]
I am trying to get started with unittest, but I am having a problem getting `setUpClass()` to work. Here is my test code... ``` import unittest class TestRepGen(unittest.TestCase): """ Contains methods for training data testing """ testvar = None @classmethod def setUpClass(cls): cls.testvar...
setUpClass is new to the unittest framework as of 2.7 and 3.2. If you want to use it with an older version you will need to use nose as your test runner instead of unittest.
How to create table during Django tests with managed = False
7,020,966
18
2011-08-11T04:50:44Z
7,035,002
12
2011-08-12T02:22:09Z
[ "python", "django", "unit-testing" ]
I have a model with managed = False. ``` class SampleModel(models.Model): apple = models.CharField(max_length=30) orange = models.CharField(max_length=30) class Meta: managed = False ``` I have a unit test which creates a SampleModel, however when I run the test I get: ``` DatabaseError: no such...
Check out this blog post: <http://www.caktusgroup.com/blog/2010/09/24/simplifying-the-testing-of-unmanaged-database-models-in-django/> It describes in detail the creation of a test runner for unmanaged models.
Python thinks I'm passing more arguments than I am?
7,022,338
10
2011-08-11T07:30:48Z
7,022,361
12
2011-08-11T07:32:57Z
[ "python", "sockets", "jython" ]
Trying to set up some basic socket code in Python (well, Jython, but I don't think that's relevant here). ``` import socket class Foo(object): def __init__(self): #some other init code here s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect("localhost", 2057) s.send("T...
You have to pass a Tuple to `connect()` method. ``` s.connect( ('localhost', 2057) ) ``` The first (implicit) argument expected is `self`, the second is the Tuple.
Python thinks I'm passing more arguments than I am?
7,022,338
10
2011-08-11T07:30:48Z
7,022,367
9
2011-08-11T07:33:38Z
[ "python", "sockets", "jython" ]
Trying to set up some basic socket code in Python (well, Jython, but I don't think that's relevant here). ``` import socket class Foo(object): def __init__(self): #some other init code here s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect("localhost", 2057) s.send("T...
You *are* passing three arguments! `s` is being passed as the implicit first argument, and the other two arguments you have specified are the second and third arguments. Now, the reason that it's upset is because `socket.connect()` only takes one argument (two, of course, if you count the implicit instance argument): ...
Python: "breaking out" of if statement inside a for loop
7,022,631
7
2011-08-11T08:00:51Z
7,022,672
9
2011-08-11T08:05:13Z
[ "python", "if-statement", "for-loop", "break" ]
I understand that one cannot "break" an if statement and only from a loop, however, I'm trying to conceptually stop an if statement from evaluating after it finds a "true" the first time when it's inside a for loop. ``` # Import XML Parser import xml.etree.ElementTree as ET # Parse XML directly from the file path tre...
``` if randomValue <= sum(i.freq for i in diceList[0:i+1]): print 'O', i, 'randomValue', randomValue, 'prob container', sum(i.freq for i in diceList[0:i+1]) break ``` [Break](http://docs.python.org/reference/simple_stmts.html#the-break-statement) will terminate "the nearest enclosing loop,...
Flask - configure dev server to be visible across the network
7,023,052
136
2011-08-11T08:40:28Z
7,027,113
230
2011-08-11T13:53:42Z
[ "python", "configuration", "flask", "devserver" ]
I'm not sure if this is Flask specific, but when I run an app in dev mode (`http://localhost:5000`), I cannot access it from other machines on the network (with `http://[dev-host-ip]:5000`). With Rails in dev mode, for example, it works fine. I couldn't find any docs regarding the Flask dev server configuration. Any id...
Add a parameter to your `app.run()`. By default it runs on localhost, change it to `app.run(host= '0.0.0.0')` to run on your machines IP address. Documented on the Flask site under "Externally Visible Server" on the [Quickstart page](http://flask.pocoo.org/docs/quickstart/#a-minimal-application): > Externally Visible...
converting a date to string for manipulation in python
7,023,641
2
2011-08-11T09:30:03Z
7,023,733
8
2011-08-11T09:37:56Z
[ "python", "datetime" ]
I am new to python and i have written a script that converts a string date coming in to a `datetime` format going out. My problem is that cannot convert the `datetime` object back to a string for manipulation. i have a date eg `2011-08-10 14:50:10` all i need to to is add a `T` between the date and time and a `Z` at th...
``` toValue = fromValue.strftime("%Y-%m-%dT %H:%M:%SZ") ``` This should work fine. `datetime.strftime` was available on Python 2.3. You'd certainly be better off upgrading to **at least** Python 2.5 if at all possible. Python 2.3 hasn't even received security patches in years. Edit: Also, you don't need to initializ...
python metaclasses at module level
7,023,932
11
2011-08-11T09:55:49Z
7,026,852
8
2011-08-11T13:38:45Z
[ "python", "python-3.x", "metaclass" ]
I read [What is a metaclass in Python?](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python/6581949#6581949) and I tried to replicate the upper metaclass from the example and found that this doesn't work in all cases: ``` def upper(cls_name, cls_parents, cls_attr): ...
The module level metaclass isn't really "module level", it has to do with how class initialization worked. The class creation would look for the variable `"__metaclass__"` when creating the class, and if it wasn't in the local environment it would look in the global. Hence, if you had a "module level" `__metaclass__` t...
How to change file access permissions in linux?
7,023,981
5
2011-08-11T09:59:28Z
7,024,070
20
2011-08-11T10:07:47Z
[ "python" ]
How does one change file access permissions? ``` f = open('test','w') f.close() ``` Defaults access permissions: 10600
You can use [os.chmod](http://docs.python.org/library/os.html#os.chmod) ``` os.chmod(path, mode) ``` You probably want to use an octal integer literal, like 0777 for the mode.
python global name 'self' is not defined
7,024,452
2
2011-08-11T10:41:07Z
7,024,476
10
2011-08-11T10:43:00Z
[ "python", "variables", "self" ]
Just started learning python and I am sure its a stupid question but I am trying something like this: ``` def setavalue(self): self.myname = "harry" def printaname(): print "Name", self.myname def main(): printname() if __name__ == "__main__": main() ``` The ...
`self` is the self-reference in a Class. Your code is not in a class, you only have functions defined. You have to wrap your methods in a class, like below. To use the method `main()`, you first have to instantiate an object of your class and call the function on the object. Further, your function `setavalue` should b...
Using a class instance as a class attribute, descriptors, and properties
7,024,915
8
2011-08-11T11:18:47Z
7,025,469
10
2011-08-11T12:01:41Z
[ "python", "class", "properties", "descriptor", "new-style-class" ]
I have recently stated trying to use the newer style of classes in Python (those derived from object). As an excersise to familiarise myself with them I am trying to define a class which has a number of class instances as attributes, with each of these class instances describing a different type of data, e.g. 1d lists,...
First, it's good you're learning new-style classes. They've got lots of advantages. The modern way to make properties in Python is: ``` class Collection(object): def __init__(self): self._profiles_1d = None @property def profiles(self): """One dimensional profiles""" return self._...
Python: Know the second wednesday of the next month with a given date
7,025,028
3
2011-08-11T11:26:22Z
7,025,262
7
2011-08-11T11:46:28Z
[ "python", "calendar", "date" ]
I would like to know this: I have for example this date: ``` 2011-08-10 wednesday ``` and i would like to know the next second wednesday of the next month: The answer should be `2011-09-14 wednesday`.
In the comments it was explained that the OP is looking for a function which maps 1. 2011-08-25 (the fourth Thursday) to 2011-09-22 (the fourth Thursday of the next month) and 2. 2011-08-30 (the fifth Tuesday) to 2011-09-27 (the fourth Tuesday, because there is no fifth Tuesday in September.) --- Using [dateut...
else & elif statements not working in Python
7,025,443
13
2011-08-11T11:59:27Z
7,025,565
19
2011-08-11T12:08:02Z
[ "python" ]
I'm a newbie to Python and currently learning Control Flow commands like `if`, `else`, etc. The `if` statement is working all fine, but when I write `else` or `elif` commands, the interpreter gives me a syntax error. I'm using Python 3.2.1 and the problem is arising in both its native interpreter and IDLE. I'm follow...
It looks like you are entering a blank line after the body of the `if` statement. This is a cue to the interactive compiler that you are done with the block entirely, so it is not expecting any `elif`/`else` blocks. Try entering the code exactly like this, and only hit enter *once* after each line: ``` if guess == num...
How can I group equivalent items together in a Python list?
7,025,581
6
2011-08-11T12:09:03Z
7,025,601
24
2011-08-11T12:10:52Z
[ "python", "list" ]
I have a list like ``` x = [2, 2, 1, 1, 1, 1, 1, 1] ``` I would like to put the repeated numbers together like ``` [[2,2],[1,1,1,1,1,1]] ```
``` [list(g) for k, g in itertools.groupby(iterable)] ``` This is exactly what [`itertools.groupby`](http://docs.python.org/library/itertools.html#itertools.groupby) is for. If you want nonconsecutive numbers grouped, like in the comment by @Michal, ``` [list(g) for k, g in itertools.groupby(sorted(iterable))] ```
Is there a library for splitting sentence into a list of words in it?
7,026,620
5
2011-08-11T13:22:49Z
7,027,334
8
2011-08-11T14:07:25Z
[ "python", "regex", "nlp" ]
I'm looking at nltk for python, but it splits(tokenize) `won't` as `['wo',"n't"]`. Are there libraries that do this more robustly? I know i can build a regex of some sort to solve this problem, but I'm looking for a library/tool because it would be a more directed approach. For example, after a basic regex with period...
[The Natural Language Toolkit](http://www.nltk.org/) (NLTK) is probably what you need. ``` >>> from nltk.tokenize import word_tokenize >>> word_tokenize("'Hello. This is a test. It works!") ["'Hello", '.', 'This', 'is', 'a', 'test', '.', 'It', 'works', '!'] >>> word_tokenize("I won't fix your computer") ['I', 'wo', "...
How can I use bcrypt/scrypt on appengine for Python?
7,027,196
23
2011-08-11T13:59:26Z
7,028,754
7
2011-08-11T15:38:20Z
[ "python", "google-app-engine", "authentication", "encryption" ]
I want make an authentication system for my app along the lines of [SUAS](https://github.com/aht/suas), except instead of using SHA256 for hashing passwords I'd like to [use bcrypt](http://codahale.com/how-to-safely-store-a-password) or scrypt. Unfortunately both py-bcrypt and scrypt for python use native c, which is u...
This [guy](http://groups.google.com/group/google-appengine-python/browse_thread/thread/36fe567ccece8e14) ported py-bcrypt to pure python so you can use it on GAE: <https://github.com/erlichmen/py-bcrypt>
How can I use bcrypt/scrypt on appengine for Python?
7,027,196
23
2011-08-11T13:59:26Z
7,029,369
24
2011-08-11T16:19:06Z
[ "python", "google-app-engine", "authentication", "encryption" ]
I want make an authentication system for my app along the lines of [SUAS](https://github.com/aht/suas), except instead of using SHA256 for hashing passwords I'd like to [use bcrypt](http://codahale.com/how-to-safely-store-a-password) or scrypt. Unfortunately both py-bcrypt and scrypt for python use native c, which is u...
Scrypt and BCrypt are both extremely processor-intensive (by design). Because of this, I very much doubt any pure-python implementation is going to be fast enough to be secure - that is, be able to hash using a sufficient number of rounds within a reasonable amount of time. I can personally attest to this, I've tried ...