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
Is Python interpreted or compiled or both?
6,889,747
62
2011-07-31T13:31:51Z
6,889,786
9
2011-07-31T13:40:52Z
[ "python", "interpreted-language" ]
From my understanding : **Interpreted** : *A high level language run and executed by an Interpreter(a program which converts the high-level language to machine code and then executing) on the go; It processes the program a little at a time.* **Compiled** : *A high level language whose code is first converted to machi...
The CPU can only understand machine code indeed. For interpreted program, the ultimate goal of an interpreter is to "interpret" the program code into machine code. However, usually a modern interpreted language does not interpret human code directly because it is too inefficient. The Python interpreter first read the ...
Is Python interpreted or compiled or both?
6,889,747
62
2011-07-31T13:31:51Z
6,889,798
90
2011-07-31T13:43:23Z
[ "python", "interpreted-language" ]
From my understanding : **Interpreted** : *A high level language run and executed by an Interpreter(a program which converts the high-level language to machine code and then executing) on the go; It processes the program a little at a time.* **Compiled** : *A high level language whose code is first converted to machi...
First off, interpreted/compiled is not a property of the language but a property of the implementation. For most languages, most if not all implementations fall in one category, so one might save a few words saying the language is interpreted/compiled too, but it's still an important distinction, both because it aids u...
python how to search an item in a nested list
6,889,785
4
2011-07-31T13:40:24Z
6,889,801
10
2011-07-31T13:44:01Z
[ "python", "list", "nested", "nested-lists" ]
say I have this list: ``` li = [["0", "20", "ar"], ["20", "40", "asdasd"], ["50", "199", "bar"], ["24", "69", "sarkozy"]] ``` Now, forget about the numbers, they are something that let me recognize the position of string. So basically, given that I have the string "ar" in hand, how can I extract all the lists that co...
``` >>> [x for x in li if 'ar' in x[2]] [['0', '20', 'ar'], ['50', '199', 'bar'], ['24', '69', 'sarkozy']] ```
Best practices for preventing Denial of Service Attack in Django
6,889,882
13
2011-07-31T14:02:30Z
6,895,885
7
2011-08-01T08:30:21Z
[ "python", "django", "security", "denial-of-service" ]
What are the best practices in Django to detect and prevent DoS attacks... Are there any ready to use apps or middleware available which prevents website access and scan through bots?
You might want to read the following 3 questions over on [Security Stack Exchange](http://security.stackexchange.com). A quick description of the problem: * [How does DoS/DDoS attack work?](http://security.stackexchange.com/q/4667/485) Possible solutions and limitations of attempting mitigation in software: * [How ...
How to find the last occurrence of an item in a Python list
6,890,170
28
2011-07-31T14:58:33Z
6,890,187
7
2011-07-31T15:02:03Z
[ "python", "list", "last-occurrence" ]
Say I have this list: ``` li = ["a", "b", "a", "c", "x", "d", "a", "6"] ``` As far as help showed me, there is not a builtin function that returns the last occurrence of a string (like the reverse of `index`). So basically, how can I find the last occurrence of `"a"` in the given list?
``` >>> (x for x in reversed([y for y in enumerate(li)]) if x[1] == 'a').next()[0] 6 >>> len(li) - (x for x in (y for y in enumerate(li[::-1])) if x[1] == 'a').next()[0] - 1 6 ```
How to find the last occurrence of an item in a Python list
6,890,170
28
2011-07-31T14:58:33Z
6,890,255
40
2011-07-31T15:12:51Z
[ "python", "list", "last-occurrence" ]
Say I have this list: ``` li = ["a", "b", "a", "c", "x", "d", "a", "6"] ``` As far as help showed me, there is not a builtin function that returns the last occurrence of a string (like the reverse of `index`). So basically, how can I find the last occurrence of `"a"` in the given list?
If you are actually using just single letters like shown in your example, then `''.join(li).rfind('a')` would work nicely. It will return `-1` if 'a' is not in the list. For the general case you could use: ``` len(li) - 1 - li[::-1].index('a') ``` It will raise `ValueError` if `'a'` is not in the list. For the case...
How to find the last occurrence of an item in a Python list
6,890,170
28
2011-07-31T14:58:33Z
23,146,126
10
2014-04-18T01:39:56Z
[ "python", "list", "last-occurrence" ]
Say I have this list: ``` li = ["a", "b", "a", "c", "x", "d", "a", "6"] ``` As far as help showed me, there is not a builtin function that returns the last occurrence of a string (like the reverse of `index`). So basically, how can I find the last occurrence of `"a"` in the given list?
Many of the other solutions require iterating over the entire list. This does not. ``` def find_last(lst, elm): gen = (len(lst) - 1 - i for i, v in enumerate(reversed(lst)) if v == elm) return next(gen, None) ``` Edit: In hindsight this seems like unnecessary wizardry. I'd do something like this instead: ``` def...
How to find the last occurrence of an item in a Python list
6,890,170
28
2011-07-31T14:58:33Z
23,816,108
7
2014-05-22T20:04:47Z
[ "python", "list", "last-occurrence" ]
Say I have this list: ``` li = ["a", "b", "a", "c", "x", "d", "a", "6"] ``` As far as help showed me, there is not a builtin function that returns the last occurrence of a string (like the reverse of `index`). So basically, how can I find the last occurrence of `"a"` in the given list?
A one-liner that's like Ignacio's except a little simpler/clearer would be ``` max(loc for loc, val in enumerate(li) if val == 'a') ``` It seems very clear and Pythonic to me: you're looking for the highest index that contains a matching value. No nexts, lambdas, reverseds or itertools required.
Python Strange Error: "TypeError: 'NoneType' object is not callable"
6,891,477
6
2011-07-31T18:34:00Z
6,891,512
10
2011-07-31T18:40:25Z
[ "python" ]
I'm implementing a simple class to represent a 2D vector. Here's are the relevant bits: ``` class Vector: def __init__( self, x, y ): self.vec_repr = x, y def __add__( self, other ): new_x = self.x + other.x new_y = self.y + other.y return Vector( new_x, new_y ) def __getattr__( self, name ): ...
The problem is that your `__getattr__` doesn't return anything for attributes other than `x` and `y` and doesn't raise an AttributeError. Hence when the `__add__` method is looked up, `__getattr__` returns `None` and hence your error. You could fix this by making `__getattr__` return values for other attributes. In fa...
Clearing the screen in IPython
6,892,191
5
2011-07-31T20:44:18Z
6,892,246
13
2011-07-31T20:54:54Z
[ "python", "windows", "ipython" ]
Is there a command in IPython to clear the screen? **EDIT:** As @Saher mentions below, I can [clean the screen](http://stackoverflow.com/questions/1432480/any-way-to-clear-python-shell) using `import os; os.system('CLS')`, but is there a way to do this without having to import all of `os`?
You can bind it to the common Ctrl-l shortcut by putting this into your `~/.ipython/ipythonrc`: ``` readline_parse_and_bind "\C-l": clear-screen ```
Clearing the screen in IPython
6,892,191
5
2011-07-31T20:44:18Z
6,892,306
11
2011-07-31T21:05:52Z
[ "python", "windows", "ipython" ]
Is there a command in IPython to clear the screen? **EDIT:** As @Saher mentions below, I can [clean the screen](http://stackoverflow.com/questions/1432480/any-way-to-clear-python-shell) using `import os; os.system('CLS')`, but is there a way to do this without having to import all of `os`?
Try `!CLS`. See <http://ipython.scipy.org/doc/rel-0.9.1/html/interactive/reference.html#id1>
Data Migrations and AppEngine
6,892,408
5
2011-07-31T21:22:49Z
6,892,484
7
2011-07-31T21:38:07Z
[ "python", "ruby-on-rails-3", "google-app-engine", "data-migration" ]
I've done a lot of development in rails, and am looking into developing projects using python & app engine. From the demo project and what I've seen so far, I've got a question/concern about app engine projects: How is data migration handled in app-engine? For example, if I change the name of an entity/table (ex: Tex...
The short answer is: It doesn't handle it. You can't change the name of an entity, you can change a property but you'll have to update the data manually. Your Model definitions are just your applications "view" of how to interpret the entities stored in the datastore. If I had a definition like: ``` class MyEntity(db...
Python byte buffer object?
6,892,570
8
2011-07-31T21:54:27Z
6,892,600
9
2011-07-31T21:59:35Z
[ "python", "buffer" ]
Is there a byte buffer object in Python to which I can append values of specific types? *(preferably with specifiable endianess)* For example: ``` buf.add_int(4) # should add a 4 byte integer buf.add_short(10) # should add a 2 byte short buf.add_byte(24) # should add a byte ``` I know that I could just use `stru...
You can always use [bitstring](http://code.google.com/p/python-bitstring/). It is capable of doing all the things you ask and more. ``` >>> import bitstring >>> stream=bitstring.BitStream() >>> stream.append("int:32=4") >>> stream.append("int:16=10") >>> stream.append("int:8=24") >>> stream BitStream('0x00000004000a18...
Trying to combine this list of unicode strings
6,892,585
2
2011-07-31T21:56:56Z
6,892,602
9
2011-07-31T21:59:42Z
[ "python", "string", "unicode" ]
Trying to combine this list of unicode strings. I've tried both using sum as well as using join. No luck. Any idea how I can do this? I just want a plain text output of all of these strings as one large string. ``` [u'\nPanera Bread (NASDAQ: <a class="ticker" href="/stock/pnra#NASDAQ">PNRA</a>) is down 6 percent toda...
Use unicode.join. ``` u''.join(that_list) ```
Python: multiplication override
6,892,616
10
2011-07-31T22:02:32Z
6,892,635
18
2011-07-31T22:05:52Z
[ "python", "override", "operator-keyword" ]
So, I've got a custom class that has a `__mul__` function which works with ints. However, in my program (in libraries), it's getting called the other way around, i.e., `2 * x` where `x` is of my class. Is there a way I can have it use my `__mul__` function for this?
Just add the following to the class definition and you should be good to go: ``` __rmul__ = __mul__ ```
Python: multiplication override
6,892,616
10
2011-07-31T22:02:32Z
6,892,636
13
2011-07-31T22:05:55Z
[ "python", "override", "operator-keyword" ]
So, I've got a custom class that has a `__mul__` function which works with ints. However, in my program (in libraries), it's getting called the other way around, i.e., `2 * x` where `x` is of my class. Is there a way I can have it use my `__mul__` function for this?
Implement `__rmul__` as well. ``` class Foo(object): def __mul__(self, other): print '__mul__' return other def __rmul__(self, other): print '__rmul__' return other x = Foo() 2 * x # __rmul__ x * 2 # __mul__ ```
how to get the return value from a thread in python?
6,893,968
109
2011-08-01T03:20:30Z
6,894,023
80
2011-08-01T03:34:36Z
[ "python", "multithreading" ]
How can I access that return value 'foo' from the thread? ``` def foo(bar): print 'hello {0}'.format(bar) return 'foo' from threading import Thread t = Thread(target=foo, args=('world!',)) t.start() x = t.join() print x ``` The one obvious way to do it, above, seems to just return `None` in x.
One way I've seen is to pass a mutable object, such as a list or a dictionary, to the thread's constructor, along with a an index or other identifier of some sort. The thread can then store its results in its dedicated slot in that object. For example: ``` def foo(bar, result, index): print 'hello {0}'.format(bar)...
how to get the return value from a thread in python?
6,893,968
109
2011-08-01T03:20:30Z
14,299,004
107
2013-01-12T23:22:00Z
[ "python", "multithreading" ]
How can I access that return value 'foo' from the thread? ``` def foo(bar): print 'hello {0}'.format(bar) return 'foo' from threading import Thread t = Thread(target=foo, args=('world!',)) t.start() x = t.join() print x ``` The one obvious way to do it, above, seems to just return `None` in x.
FWIW, the `multiprocessing` module has a nice interface for this using the `Pool` class. And if you want to stick with threads rather than processes, you can just use the `multiprocessing.pool.ThreadPool` class as a drop-in replacement. ``` def foo(bar, baz): print 'hello {0}'.format(bar) return 'foo' + baz from ...
how to get the return value from a thread in python?
6,893,968
109
2011-08-01T03:20:30Z
14,331,755
29
2013-01-15T05:38:45Z
[ "python", "multithreading" ]
How can I access that return value 'foo' from the thread? ``` def foo(bar): print 'hello {0}'.format(bar) return 'foo' from threading import Thread t = Thread(target=foo, args=('world!',)) t.start() x = t.join() print x ``` The one obvious way to do it, above, seems to just return `None` in x.
Jake's answer is good, but if you don't want to use a threadpool (you don't know how many threads you'll need, but create them as needed) then a good way to transmit information between threads is the built-in [Queue.Queue](http://docs.python.org/2/library/queue.html) class, as it offers thread safety. I created the f...
how to get the return value from a thread in python?
6,893,968
109
2011-08-01T03:20:30Z
25,072,068
9
2014-08-01T02:39:12Z
[ "python", "multithreading" ]
How can I access that return value 'foo' from the thread? ``` def foo(bar): print 'hello {0}'.format(bar) return 'foo' from threading import Thread t = Thread(target=foo, args=('world!',)) t.start() x = t.join() print x ``` The one obvious way to do it, above, seems to just return `None` in x.
I stole kindall's answer and cleaned it up just a little bit. The key part is adding \*args and \*\*kwargs to join() in order to handle the timeout ``` class threadWithReturn(Thread): def __init__(self, *args, **kwargs): super(threadWithReturn, self).__init__(*args, **kwargs) self._return = None ...
using query string in Python Pyramid route configuration
6,896,943
6
2011-08-01T10:10:56Z
7,029,607
10
2011-08-11T16:36:09Z
[ "python", "forms", "routes", "pyramid", "deform" ]
this is very specific to what I am trying to do so I start describing what it is: * a Pyramid app serving plots like <http://localhost:6543/path/to/myplot/plot001.png> * if the plot is not available another image is served (work.png) * another part is the deform view which provides a HTML form to enter the configurati...
There are two ways to do this depending on what you prefer for separating your code. 1. Put all of the logic into your view, separated by 'if' statements on `request.GET.get('action')`. ``` config.add_route('plot', '/{project_name}/testruns/{testrun_name}/plots/{plot_name}.png') config.scan() @view_confi...
Does whoosh require all strings to be unicode?
6,897,042
3
2011-08-01T10:20:53Z
7,086,826
8
2011-08-17T00:48:18Z
[ "python", "whoosh" ]
I am redoing my search app in Whoosh from Solr. I am now learning from the **quick start**. But I kept running into problems each time I had to deal with strings `>>>writer.add_document(iden=fil, content=F2T.file_to_text(fil_path))` `ValueError: 'File Name.doc' is not unicode or sequence` and then: ``` >>>query = Qu...
Yes, it requires strings are in Unicode. ``` query = QueryParser("content", ix.schema).parse("first") ``` Change that to: ``` query = QueryParser("content", ix.schema).parse(u"first") ```
How to override a field in the parent class
6,897,730
10
2011-08-01T11:27:03Z
6,899,713
13
2011-08-01T14:13:31Z
[ "python", "django", "class", "override" ]
I have parent and child classes in Django model. And I want to fill a field in parent class when initialize child class. Or override this field in child class. ``` class Parent(models.Model): type = models.CharField() class Child(Parent): type = models.CharField() //Doesn't work ``` Also try...
> In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this is not permitted for attributes that are Field instances (at least, not at the moment). If a base class has a field called author, you cannot create another model field called autho...
How to know the position of items in a Python's ordered dictionary
6,897,750
20
2011-08-01T11:28:32Z
6,897,813
36
2011-08-01T11:34:10Z
[ "python", "ordereddictionary" ]
Can we know the position of items in Python's ordered dictionary ? For example: If I have dictionary : ``` // Ordered_dict is OrderedDictionary Ordered_dict = {"fruit": "banana", "drinks": "water", "animal": "cat"} ``` Now how to know in which position cat belongs to? Is it possible to get answer like: `position...
You may get list of keys with the `keys` property: ``` In [20]: d=OrderedDict((("fruit", "banana"), ("drinks", 'water'), ("animal", "cat"))) In [21]: d.keys().index('animal') Out[21]: 2 ``` A better performance could be achieved with the use of `iterkeys()` though. For those using Python 3 ``` >>> list(x.keys()).i...
Confused about Python's with statement
6,898,257
5
2011-08-01T12:15:08Z
6,898,329
9
2011-08-01T12:21:50Z
[ "python" ]
I saw some code in the Whoosh documentation: ``` with ix.searcher() as searcher: query = QueryParser("content", ix.schema).parse(u"ship") results = searcher.search(query) ``` I read that the with statement executes \_\_ enter\_\_ and \_\_ exit\_\_ methods and they are really useful in the forms "with file\_po...
Example straight from [PEP-0343](http://www.python.org/dev/peps/pep-0343/): ``` with EXPR as VAR: BLOCK #translates to: mgr = (EXPR) exit = type(mgr).__exit__ # Not calling it yet value = type(mgr).__enter__(mgr) exc = True try: try: VAR = value # Only if "as VAR" is present BLOCK except...
which one should I use: os.sep or os.path.sep?
6,900,520
30
2011-08-01T15:13:31Z
6,900,583
8
2011-08-01T15:17:19Z
[ "python", "operating-system" ]
They are same, but which one should I use? <http://docs.python.org/library/os.html>: > `os.sep` > > > The character used by the operating system to separate pathname components. This is '/' for POSIX and '\' for Windows. Note that knowing this is not sufficient to be able to parse or concatenate pathnames — use os....
I recommend you use `os.path.sep` for clarity, since it's a path separator, not an OS separator. If you `import os.path as path` you can call it `path.sep`, which is even better.
which one should I use: os.sep or os.path.sep?
6,900,520
30
2011-08-01T15:13:31Z
6,900,592
36
2011-08-01T15:17:55Z
[ "python", "operating-system" ]
They are same, but which one should I use? <http://docs.python.org/library/os.html>: > `os.sep` > > > The character used by the operating system to separate pathname components. This is '/' for POSIX and '\' for Windows. Note that knowing this is not sufficient to be able to parse or concatenate pathnames — use os....
I'd use `os.path.sep` to make it very clear that it's the path separator… But consistency is more important, so if one is already being used, use that. Otherwise, pick one and use it all the time. **Edit**: Just to make sure you're not reinventing the wheel, though, the `path` module already has `join`, `split`, `di...
Python "expected an indented block"
6,901,436
10
2011-08-01T16:25:06Z
6,901,476
10
2011-08-01T16:28:36Z
[ "python" ]
Let me start off by saying that I am COMPLETELY new to programming. I have just recently picked up Python and it has consistently kicked me in the head with one recurring error -- "expected an indented block" Now, I know there are several other threads addressing this problem and I have looked over a good number of the...
Starting with `elif option == 2:`, you indented one time too many. In a decent text editor, you should be able to highlight these lines and press `Shift`+`Tab` to fix the issue. Additionally, there is no statement after `for x in range(x, 1, 1):`. Insert an indented `pass` to do nothing in the `for` loop. Also, in th...
Why is Python's Hashlib not strongly typed?
6,901,706
3
2011-08-01T16:47:37Z
6,901,738
11
2011-08-01T16:50:21Z
[ "python", "hashlib" ]
Python is supposed to be strongly typed. For instance: `'abc'['1']` won't work, because you're expected to provide an integer there, not a string. An error wil be raised and you can go on and correct it. But that's not the case with hashlib. Indeed, try the following: ``` import hashlib hashlib.md5('abc') #Works OK ...
It's not just hashlib - Python 2 handles Unicode in a number of places by trying to encode it as ascii. This was one of the big changes made for Python 3. In Python 3, strings are unicode, and they behave as you expect: there's no automatic conversion to bytes, and you have to encode them if you want to use bytes (e.g...
Invoking a PowerShell script from Python
6,901,856
11
2011-08-01T17:00:39Z
6,901,967
11
2011-08-01T17:14:45Z
[ "python", "powershell" ]
I'm trying to start a PowerShell script from python like this: ``` psxmlgen = subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe', './buildxml.ps1', arg1, arg2, arg3], cwd=os.getcwd()) result = psxmlgen.wait() ``` The problem is that...
First, `Set-ExecutionPolicy Unrestriced` is on a per user basis, and a per bitness basis (32-bit is different than 64-bit). Second, you can override the execution policy from the command line. ``` psxmlgen = subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe', '...
Why are slices in Python 3 still copies and not views?
6,902,235
45
2011-08-01T17:43:10Z
6,902,980
10
2011-08-01T18:56:24Z
[ "python", "python-3.x", "language-design", "slice" ]
As I only now noticed after commenting on [this answer](http://stackoverflow.com/questions/6900955/python-convert-list-to-dictionary/6900977#6900977), slices in Python 3 return shallow copies of whatever they're slicing rather than views. Why is this still the case? Even leaving aside numpy's usage of views rather than...
> As well, the fact that you can use assignment to slices to modify the original list, but slices are themselves copies and not views. Hmm.. that's not quite right; although I can see how you might think that. In other languages, a slice assignment, something like: ``` a[b:c] = d ``` is equivalent to ``` tmp = a.op...
Why does __init__ not get called if __new__ called with no args
6,903,355
6
2011-08-01T19:28:42Z
6,903,458
9
2011-08-01T19:36:39Z
[ "python" ]
I am trying to create (not exactly restore) an object which has its attributes saved in a database. Therefore, I do not want to call `__init__`. This desire appears to be inline with [Guido's intended use for `__new__`](http://python-history.blogspot.com/2010/06/inside-story-on-new-style-classes.html). I do not underst...
The **constructor** (`User()`) is responsible for calling the **allocator** (`User.__new__()`) and the **initializer** (`User.__init__()`) in turn. Since the constructor is never invoked, the initializer is never called.
Why does __init__ not get called if __new__ called with no args
6,903,355
6
2011-08-01T19:28:42Z
6,903,468
10
2011-08-01T19:37:24Z
[ "python" ]
I am trying to create (not exactly restore) an object which has its attributes saved in a database. Therefore, I do not want to call `__init__`. This desire appears to be inline with [Guido's intended use for `__new__`](http://python-history.blogspot.com/2010/06/inside-story-on-new-style-classes.html). I do not underst...
Because you're bypassing the usual construction mechanism, by calling `__new__` directly. The `__init__`-after-`__new__` logic is in `type.__call__` (in CPython see `typeobject.c`, `type_call` function), so it happens only when you'd do `User(...)`.
How to print a string literally in Python
6,903,551
8
2011-08-01T19:44:52Z
6,903,563
21
2011-08-01T19:46:11Z
[ "python", "ansi-escape" ]
this is probably really simple but I can't find it. I need to print what a string in Python contains. I'm collecting data from a serial port and I need to know if it is sending CR or CRLF + other control codes that are not ascii. As an example say I had ``` s = "ttaassdd\n\rssleeroo" ``` then I would like to do is:...
Try with: ``` print repr(s) >>> 'ttaassdd\n\rssleeroo' ```
Splitting on first occurrence
6,903,557
107
2011-08-01T19:45:21Z
6,903,583
31
2011-08-01T19:47:47Z
[ "python", "split" ]
What would be the best way to split a string on the first occurrence of a delimiter? For example: `123mango abcd mango kiwi peach` splitting on the first `mango` to get: ``` abcd mango kiwi peach ```
``` >>> s = "123mango abcd mango kiwi peach" >>> s.split("mango", 1) ['123', ' abcd mango kiwi peach'] >>> s.split("mango", 1)[1] ' abcd mango kiwi peach' ```
Splitting on first occurrence
6,903,557
107
2011-08-01T19:45:21Z
6,903,597
160
2011-08-01T19:48:43Z
[ "python", "split" ]
What would be the best way to split a string on the first occurrence of a delimiter? For example: `123mango abcd mango kiwi peach` splitting on the first `mango` to get: ``` abcd mango kiwi peach ```
From [the docs](http://docs.python.org/library/stdtypes.html#str.split): > `str.split([`*sep*`[,`*maxsplit*`]])` > > Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). ``` s...
Splitting on first occurrence
6,903,557
107
2011-08-01T19:45:21Z
24,116,364
12
2014-06-09T08:26:09Z
[ "python", "split" ]
What would be the best way to split a string on the first occurrence of a delimiter? For example: `123mango abcd mango kiwi peach` splitting on the first `mango` to get: ``` abcd mango kiwi peach ```
For me the better approach is that: ``` s.split('mango', 1)[-1] ``` ...because if happens that occurrence is not in the string you'll get "`IndexError: list index out of range"`. Therefore `-1` will not get any harm cause number of occurrences is already set to one.
Copying files recursively with skipping some directories in Python?
6,904,069
3
2011-08-01T20:28:58Z
6,904,085
7
2011-08-01T20:31:01Z
[ "python" ]
I want to copy a directory to another directory recursively. I also want to ignore some files (eg. all hidden files; everything starting with ".") and then run a function on all the other files (after copying them). This is simple to do in the shell, but I need a Python script. I tried using shutil.copytree, which has...
You can use [os.walk](http://docs.python.org/library/os.html#os.walk) to iterate over each file, apply your custom filtering function and copying over only the ones you care. > ``` > os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]]) > ``` > > Generate the file names in a directory tree by walking the t...
Python, pass a variable by name to a Thread
6,904,487
13
2011-08-01T21:08:44Z
6,904,509
25
2011-08-01T21:10:38Z
[ "python", "multithreading", "syntax", "syntax-error", "python-multithreading" ]
Say that I have a function that looks like: ``` def _thread_function(arg1, arg2=None, arg3=None): #Random code ``` Now I want to create a thread using that function, and giving it arg2 but not arg3. I'm trying to this as below: ``` #Note: in this code block I have already set a variable called arg1 and a variabl...
Use the [kwargs parameter](http://docs.python.org/library/threading.html#threading.Thread): ``` threading.Thread(target=self._thread_function, args=(arg1,), kwargs={'arg2':arg2}, name='thread_function').start() ```
How to match--but not capture--in Python regular expressions?
6,905,344
5
2011-08-01T22:42:38Z
6,905,402
7
2011-08-01T22:50:22Z
[ "python", "regex" ]
I've got a function spitting out "Washington D.C., DC, USA" as output. I need to capture "Washington, DC" for reasons that have to do with how I handle every single other city in the country. (Note: this is **not** the same as "D.C.", I need the comma to be between "Washington" and "DC", whitespace is fine) I can't fo...
That's a clever way indeed, but not-capturing doesn't mean removing it from match. It just mean, that it's not considered as an output group. You should try to do something similar to the following: ``` match = re.search(r'(\w+)\s(?:D\.C\.), (\w\w)\W', location).groups() ``` This prints `('Washington', 'DC')`. Note...
Python conditional list joins
6,905,636
6
2011-08-01T23:25:22Z
6,905,738
7
2011-08-01T23:40:00Z
[ "python", "string", "list" ]
I have a list that looks like this: `['A', 'must', 'see', 'is', 'the', 'Willaurie', ',', 'which', 'sank', 'after', 'genoegfuuu', 'damaged', 'in', 'a', 'storm', 'in', '1989', '.']` As you can see, there is punctuation. I want to call .join using a blankspace except for the cases where the string is punctuation, then I ...
The `string` module has a list containing all punctuation characters. ``` import string string = ''.join([('' if c in string.punctuation else ' ')+c for c in wordlist]).strip() ```
How to properly check object types in Python?
6,905,655
3
2011-08-01T23:28:29Z
6,905,678
8
2011-08-01T23:31:30Z
[ "python", "types", "comparison", "isinstance" ]
Problem: I have to check that the a returned value is a Python dictionary. Q1. Which of these options is the proper way to do this? ``` type(x) == dict type(x) == type(dict) isinstance(d, dict) ``` Then there are the other variants using `is` operator instead of `==`. Q2. [Many people](http://stackoverflow.com/qu...
> Q1. Which of these options is the proper way to do this? Don't waste time on type checking. It's error-prone because it's based on assumptions. > Q2. ... do I have any other choice? Yes do this. ``` try: x.the_dict_operation() except TypeError: # x was not the expected type for the operation raise # ...
Mac osx lion, virtualenv, pil install - gcc error
6,906,385
10
2011-08-02T01:30:36Z
6,906,560
8
2011-08-02T02:01:39Z
[ "python", "django", "osx", "python-imaging-library" ]
I have just completed the xcode install, mac osx lion. Upon completion I attempted to install PIL in a virtual enviroment using pip, easy\_install and home brew. All three are erring out. pip install give the following error: pip ` ``` unable to execute gcc-4.0: No such file or directory error: command 'gcc-4.0' fai...
Xcode 4.1 on OS X Lion 10.7 no longer includes `gcc-4.0` as it did in earlier versions of OS X. When you install a Python package like PIL that includes a C extension module, Python's Distutils will attempt to use the same version of the C compiler that that Python itself was build with. It sounds like the version of P...
itertools.groupby in a django template
6,906,593
9
2011-08-02T02:10:39Z
6,906,796
14
2011-08-02T02:57:22Z
[ "python", "django", "group-by", "django-templates", "itertools" ]
I'm having an odd problem using `itertools.groupby` to group the elements of a queryset. I have a model `Resource`: ``` from django.db import models TYPE_CHOICES = ( ('event', 'Event Room'), ('meet', 'Meeting Room'), # etc ) class Resource(models.Model): name = models.CharField(max_length=30) ...
I think that you're right. I don't understand why, but it looks to me like your `groupby` iterator is being pre-iterated. It's easier to explain with code: ``` >>> even_odd_key = lambda x: x % 2 >>> evens_odds = sorted(range(10), key=even_odd_key) >>> evens_odds_grouped = itertools.groupby(evens_odds, key=even_odd_key...
itertools.groupby in a django template
6,906,593
9
2011-08-02T02:10:39Z
16,171,518
12
2013-04-23T14:07:26Z
[ "python", "django", "group-by", "django-templates", "itertools" ]
I'm having an odd problem using `itertools.groupby` to group the elements of a queryset. I have a model `Resource`: ``` from django.db import models TYPE_CHOICES = ( ('event', 'Event Room'), ('meet', 'Meeting Room'), # etc ) class Resource(models.Model): name = models.CharField(max_length=30) ...
Django's templates want to know the length of things that are looped over using `{% for %}`, but generators don't have a length. So Django decides to convert it to a list before iterating, so that it has access to a list. This breaks generators created using `itertools.groupby`. If you don't iterate through each grou...
Error installing PyQt
6,906,856
10
2011-08-02T03:12:04Z
7,001,436
7
2011-08-09T18:57:37Z
[ "python", "pyqt" ]
I am now trying to run PyQt. I am still getting the following error when I do the following: ``` root@localhost:/home/abhowmik/app/imgSeek-0.8.6# cd Py* root@localhost:/home/abhowmik/app/imgSeek-0.8.6/PyQt-x11-gpl-4.8.4# python configure.py --verbose Determining the layout of your Qt installation... /usr/share/qt3//bi...
Problem is that configure.py is trying to use qmake from qt3. Try this: ``` python configure.py --qmake /usr/bin/qmake-qt4 ``` (You might have qmake-qt4 somwhere else than /usr/bin so check that first )
Updating context data in FormView form_valid method?
6,907,388
9
2011-08-02T04:50:42Z
8,222,609
21
2011-11-22T05:56:59Z
[ "python", "django", "django-class-based-views" ]
I have a class `QuestionView` which is derived from the `FormView` class. Here is a code snippet to explain my problem: ``` class QuestionView(FormView): ... context_var1 = y def form_valid (self, form): ... self.context_var1 = x ... def get_context_data(self, **kwargs): ... context...
I do this with `form_invalid`. Here's how I do it: ``` from django.views.generic import FormView class ContextFormView(FormView): def get(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) context = self.get_context_data(**kwargs) c...
Pythonic way of closing/terminating an object
6,907,717
3
2011-08-02T05:39:44Z
6,907,748
7
2011-08-02T05:44:54Z
[ "multithreading", "python" ]
I have a Whoosh (file indexer) writer object ``` >>> a <whoosh.filedb.filewriting.SegmentWriter object at 0x013DFE10> ``` As whoosh doesnt allow mutiple writers and implement thread safety (AFAIK!!), I would like to **close** that object when it has been used. ``` >>> a.is_closed False ``` But it has no close metho...
If it has `__enter__` and `__exit__` methods, that means it implements the [context manager protocol](http://docs.python.org/reference/datamodel.html#with-statement-context-managers), and you should use it like this: ``` with constructor(args) as a: # do stuff with a pass # here a is closed even if you had an ...
subprocess and extra args
6,908,134
2
2011-08-02T06:34:29Z
6,908,184
7
2011-08-02T06:40:20Z
[ "python", "subprocess" ]
I'm trying to use the following code: ``` args = 'LD_LIBRARY_PATH=/opt/java/jre/lib/i386/:/opt/java/jre/lib/amd64/ exec /opt/java/jre/bin/java -Xincgc -Xmx1G -jar craftbukkit-0.0.1-SNAPSHOT.jar'.split() p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) ``` However, the ...
Try adding `shell = True` to the `Popen` call: ``` p = subprocess.Popen(args, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) ``` The syntax you're using to set `LD_LIBRARY_PATH` is a shell syntax, so it's necessary to execute the command through the shell.
Should I put #! (shebang) in Python scripts, and what form should it take?
6,908,143
265
2011-08-02T06:35:42Z
6,908,180
61
2011-08-02T06:39:30Z
[ "python", "shell", "python-3.x", "shebang" ]
Should I put the shebang in my Python scripts? In what form? ``` #!/usr/bin/env python ``` or ``` #!/usr/local/bin/python ``` Are these equally portable? Which form is used most? ***Note:*** the [tornado](https://github.com/facebook/tornado) project uses the shebang. On the other hand the [Django](https://www.djan...
It's really just a matter of taste. Adding the shebang means people can invoke the script directly if they want (assuming it's marked as executable); omitting it just means `python` has to be invoked manually. The end result of running the program isn't affected either way; it's just options of the means.
Should I put #! (shebang) in Python scripts, and what form should it take?
6,908,143
265
2011-08-02T06:35:42Z
6,908,238
8
2011-08-02T06:45:12Z
[ "python", "shell", "python-3.x", "shebang" ]
Should I put the shebang in my Python scripts? In what form? ``` #!/usr/bin/env python ``` or ``` #!/usr/local/bin/python ``` Are these equally portable? Which form is used most? ***Note:*** the [tornado](https://github.com/facebook/tornado) project uses the shebang. On the other hand the [Django](https://www.djan...
The purpose of shebang is for the script to recognize the interpreter type when you want to execute the script from the shell. Mostly, and not always, you execute scripts by supplying the interpreter externally. Example usage: `python-x.x script.py` This will work even if you don't have a shebang declarator. Why firs...
Should I put #! (shebang) in Python scripts, and what form should it take?
6,908,143
265
2011-08-02T06:35:42Z
6,908,732
10
2011-08-02T07:42:26Z
[ "python", "shell", "python-3.x", "shebang" ]
Should I put the shebang in my Python scripts? In what form? ``` #!/usr/bin/env python ``` or ``` #!/usr/local/bin/python ``` Are these equally portable? Which form is used most? ***Note:*** the [tornado](https://github.com/facebook/tornado) project uses the shebang. On the other hand the [Django](https://www.djan...
You should add a shebang if the script is intended to be executable. You should also install the script with an installing software that modifies the shebang to something correct so it will work on the target platform. Examples of this is distutils and Distribute.
Should I put #! (shebang) in Python scripts, and what form should it take?
6,908,143
265
2011-08-02T06:35:42Z
14,599,026
7
2013-01-30T07:52:16Z
[ "python", "shell", "python-3.x", "shebang" ]
Should I put the shebang in my Python scripts? In what form? ``` #!/usr/bin/env python ``` or ``` #!/usr/local/bin/python ``` Are these equally portable? Which form is used most? ***Note:*** the [tornado](https://github.com/facebook/tornado) project uses the shebang. On the other hand the [Django](https://www.djan...
Sometimes, if the answer is not very clear (I mean you cannot decide if yes or no), then it does not matter too much, and you can ignore the problem until the answer *is* clear. The `#!` only purpose is for launching the script. Django loads the sources on its own and uses them. It never needs to decide what interpret...
Should I put #! (shebang) in Python scripts, and what form should it take?
6,908,143
265
2011-08-02T06:35:42Z
18,165,365
9
2013-08-10T18:57:46Z
[ "python", "shell", "python-3.x", "shebang" ]
Should I put the shebang in my Python scripts? In what form? ``` #!/usr/bin/env python ``` or ``` #!/usr/local/bin/python ``` Are these equally portable? Which form is used most? ***Note:*** the [tornado](https://github.com/facebook/tornado) project uses the shebang. On the other hand the [Django](https://www.djan...
If you have more than one version of Python and the script needs to run under a specific version, the she-bang can ensure the right one is used when the script is executed directly, for example: ``` #!/usr/bin/python2.7 ``` Note the script could still be run via a complete Python command line, or via import, in which...
Should I put #! (shebang) in Python scripts, and what form should it take?
6,908,143
265
2011-08-02T06:35:42Z
19,305,076
360
2013-10-10T19:58:55Z
[ "python", "shell", "python-3.x", "shebang" ]
Should I put the shebang in my Python scripts? In what form? ``` #!/usr/bin/env python ``` or ``` #!/usr/local/bin/python ``` Are these equally portable? Which form is used most? ***Note:*** the [tornado](https://github.com/facebook/tornado) project uses the shebang. On the other hand the [Django](https://www.djan...
The shebang line in any script determines the script's ability to be executed like an standalone executable without typing `python` beforehand in the terminal or when double clicking it in a file manager(when configured properly). It isn't necessary but generally put there so when someone sees the file opened in an edi...
Should I put #! (shebang) in Python scripts, and what form should it take?
6,908,143
265
2011-08-02T06:35:42Z
31,954,823
8
2015-08-12T01:58:47Z
[ "python", "shell", "python-3.x", "shebang" ]
Should I put the shebang in my Python scripts? In what form? ``` #!/usr/bin/env python ``` or ``` #!/usr/local/bin/python ``` Are these equally portable? Which form is used most? ***Note:*** the [tornado](https://github.com/facebook/tornado) project uses the shebang. On the other hand the [Django](https://www.djan...
> Should I put the shebang in my Python scripts? Put a shebang into a Python script to indicate: * this module can be run as a script * whether it can be run only on python2, python3 or is it Python 2/3 compatible * on POSIX, it is necessary if you want to run the script directly without invoking `python` executable ...
How can I sort a specific range of elements in a list?
6,908,384
2
2011-08-02T07:05:11Z
6,908,416
10
2011-08-02T07:08:21Z
[ "python", "algorithm", "list", "sorting", "range" ]
Suppose I have a list, ``` lst = [5, 3, 5, 1, 4, 7] ``` and I want to get it ordered from the second element 3 to the end. I thought I could do it by: ``` lst[1:].sort() ``` But, this doesn't work. How can I do it?
``` lst = lst[0:1] + sorted(lst[1:]) ```
How can I sort a specific range of elements in a list?
6,908,384
2
2011-08-02T07:05:11Z
6,908,437
7
2011-08-02T07:10:51Z
[ "python", "algorithm", "list", "sorting", "range" ]
Suppose I have a list, ``` lst = [5, 3, 5, 1, 4, 7] ``` and I want to get it ordered from the second element 3 to the end. I thought I could do it by: ``` lst[1:].sort() ``` But, this doesn't work. How can I do it?
``` lst = [5, 3, 5, 1, 4, 7] lst[1:] = sorted(lst[1:]) print(lst) # prints [5, 1, 3, 4, 5, 7] ```
PyAudio, how to tell frequency and amplitude while recording?
6,908,540
2
2011-08-02T07:23:07Z
6,908,766
7
2011-08-02T07:45:03Z
[ "python", "audio", "numpy", "scipy", "pyaudio" ]
I've used the PyAudio default recording example, and added numpy and scipy. I can only use `scipy.io.wavefile.read('FILE.wav')`, after recording the file, however, and it also gives me this random tuple, eg: `(44100, array([[ 0, 0], [-2, 0], [ 0, -2], ..., [-2, -2], [ 1, 3], [ 2, -1]], dtype=int16))`. What does this ar...
The array is not random data, it's the wave data of your stereo sound, and 44100 is the sampling rate. use the following code to plot the wave of left channel: ``` import scipy.io.wavfile as wavfile import numpy as np import pylab as pl rate, data = wavfile.read('FILE.wav') t = np.arange(len(data[:,0]))*1.0/rate pl.pl...
How to convert a namedtuple into a list of values and preserving the order of properties?
6,908,986
8
2011-08-02T08:08:19Z
6,909,027
17
2011-08-02T08:11:57Z
[ "python" ]
``` from collections import namedtuple Gaga = namedtuple('Gaga', ['id', 'subject', 'recipient']) g = Gaga(id=1, subject='hello', recipient='Janitor') ``` I want to be able to obtain this list (which preserves the order of the properties): ``` [1, 'hello', 'Janitor'] ``` I could create this list myself manually but t...
Why not just `list`? ``` >>> list(g) [1, 'hello', 'Janitor'] ```
How to get indices of N maximum values in a numpy array?
6,910,641
108
2011-08-02T10:29:25Z
6,910,672
69
2011-08-02T10:32:53Z
[ "python", "numpy" ]
Numpy proposes a way to get the index of the maximum value of an array via `np.argmax`. I would like a similar thing, but returning the indexes of the N maximum values. For instance, if I have an array `[1, 3, 2, 4, 5]`, it `function(array, n=3)` would return `[4, 3, 1]`. Thanks :)
The simplest I've been able to come up with is: ``` In [1]: import numpy as np In [2]: arr = np.array([1, 3, 2, 4, 5]) In [3]: arr.argsort()[-3:][::-1] Out[3]: array([4, 3, 1]) ``` This involves a complete sort of the array. I wonder if `numpy` provides a built-in way to do a partial sort; so far I haven't been abl...
How to get indices of N maximum values in a numpy array?
6,910,641
108
2011-08-02T10:29:25Z
18,691,983
15
2013-09-09T05:30:32Z
[ "python", "numpy" ]
Numpy proposes a way to get the index of the maximum value of an array via `np.argmax`. I would like a similar thing, but returning the indexes of the N maximum values. For instance, if I have an array `[1, 3, 2, 4, 5]`, it `function(array, n=3)` would return `[4, 3, 1]`. Thanks :)
EDIT: Modified to include Ashwini Chaudhary's improvement. ``` >>> import heapq >>> import numpy >>> a = numpy.array([1, 3, 2, 4, 5]) >>> heapq.nlargest(3, range(len(a)), a.take) [4, 3, 1] ``` For regular Python lists: ``` >>> a = [1, 3, 2, 4, 5] >>> heapq.nlargest(3, range(len(a)), a.__getitem__) [4, 3, 1] ``` If ...
How to get indices of N maximum values in a numpy array?
6,910,641
108
2011-08-02T10:29:25Z
23,734,295
127
2014-05-19T09:32:20Z
[ "python", "numpy" ]
Numpy proposes a way to get the index of the maximum value of an array via `np.argmax`. I would like a similar thing, but returning the indexes of the N maximum values. For instance, if I have an array `[1, 3, 2, 4, 5]`, it `function(array, n=3)` would return `[4, 3, 1]`. Thanks :)
Newer NumPy versions (1.8 and up) have a function called [`argpartition`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html) for this. To get the indices of the four largest elements, do ``` >>> a array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0]) >>> ind = np.argpartition(a, -4)[-4:] >>> ind array([1, 5,...
How to get indices of N maximum values in a numpy array?
6,910,641
108
2011-08-02T10:29:25Z
27,433,395
12
2014-12-11T22:13:05Z
[ "python", "numpy" ]
Numpy proposes a way to get the index of the maximum value of an array via `np.argmax`. I would like a similar thing, but returning the indexes of the N maximum values. For instance, if I have an array `[1, 3, 2, 4, 5]`, it `function(array, n=3)` would return `[4, 3, 1]`. Thanks :)
Simpler yet: ``` idx = (-arr).argsort()[:n] ``` where *n* is the number of maximum values.
Execute if no exception thrown
6,911,999
3
2011-08-02T12:20:48Z
6,912,019
7
2011-08-02T12:22:38Z
[ "python", "exception", "python-3.x", "try-catch", "finally" ]
I have some code I want to execute if an exception is **not** thrown. Currently I'm doing this: ``` try: return type, self.message_handlers[type](self, length - 1) finally: if not any(self.exc_info()): self.last_recv_time = time.time() ``` Can this be improved on? Is this the best way to do it? ## U...
``` try: tmp = type, self.message_handlers[type](self, length - 1) except Exception: pass #or handle error, or just "raise" to re-raise else: self.last_recv_time = time.time() return tmp ```
Execute if no exception thrown
6,911,999
3
2011-08-02T12:20:48Z
6,912,396
7
2011-08-02T12:53:51Z
[ "python", "exception", "python-3.x", "try-catch", "finally" ]
I have some code I want to execute if an exception is **not** thrown. Currently I'm doing this: ``` try: return type, self.message_handlers[type](self, length - 1) finally: if not any(self.exc_info()): self.last_recv_time = time.time() ``` Can this be improved on? Is this the best way to do it? ## U...
Your code suggests that you don't want to catch the exception if it occurs, so why not simply ``` result = type, self.message_handlers[type](self, length - 1) self.last_recv_time = time.time() return result ``` (Am I missing anything?)
Is OptionParser in conflict with sphinx?
6,912,025
11
2011-08-02T12:23:21Z
6,946,764
17
2011-08-04T18:36:37Z
[ "python", "python-sphinx", "optionparser" ]
I'm trying to write a documentation for my project in sphinx and whenever sphinx encounters OptionParser in my module it gives me: ``` sphinx-build: error: no such option: -b ``` I thought that it's impossible, so I wrote a simple module to check this: ``` from optparse import OptionParser """some comment here""" ...
Here is what I think happens: When Sphinx runs, [autodoc](http://sphinx.pocoo.org/ext/autodoc.html) imports your module and the toplevel code in the module is executed. An OptionParser instance is created, and it processes the command line arguments and options passed to sphinx-build, [one of which is **-b**](http://s...
How to split list and pass them as separate parameter?
6,913,084
10
2011-08-02T13:46:40Z
6,913,101
23
2011-08-02T13:48:11Z
[ "python", "list" ]
My problem is I have values in a list. And I want to separate these values and send them as a separate parameter. My code is: ``` def egg(): return "egg" def egg2(arg1, arg2): print arg1 print arg2 argList = ["egg1", "egg2"] arg = ', '.join(argList) egg2(arg.split()) ``` This line of code `(egg2(arg.s...
``` >>> argList = ["egg1", "egg2"] >>> egg2(*argList) egg1 egg2 ``` You can use \*args (arguments) and \*\*kwargs (for keyword arguments) when calling a function. Have a look at [this blog](http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/) on how to use it properly.
How to split list and pass them as separate parameter?
6,913,084
10
2011-08-02T13:46:40Z
6,913,104
7
2011-08-02T13:48:20Z
[ "python", "list" ]
My problem is I have values in a list. And I want to separate these values and send them as a separate parameter. My code is: ``` def egg(): return "egg" def egg2(arg1, arg2): print arg1 print arg2 argList = ["egg1", "egg2"] arg = ', '.join(argList) egg2(arg.split()) ``` This line of code `(egg2(arg.s...
There is a special syntax for [argument unpacking](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists): ``` egg2(*argList) ```
Encoding mail subject (SMTP) in Python with non-ASCII characters
6,913,170
14
2011-08-02T13:53:57Z
13,004,154
19
2012-10-22T02:03:22Z
[ "python", "utf-8", "character-encoding", "smtp", "cjk" ]
I am using Python module `MimeWriter` to construct a message and smtplib to send a mail constructed message is: ``` file msg.txt: ----------------------- Content-Type: multipart/mixed; from: me<me@abc.com> to: me@abc.com subject: 主題 Content-Type: text/plain;charset=utf-8 主題 ``` I use the code below to send ...
From <http://docs.python.org/library/email.header.html> ``` from email.message import Message from email.header import Header msg = Message() msg['Subject'] = Header('主題', 'utf-8') print msg.as_string() ``` > Subject: =?utf-8?b?5Li76aGM?= more simple: ``` from email.header import Header print Header('主題', '...
SSH into Django Shell
6,913,283
12
2011-08-02T14:00:11Z
6,913,397
17
2011-08-02T14:06:59Z
[ "python", "django", "ssh" ]
I'm attempting to write a simple one-line script to ssh into a remote host, CD to my Django app's directory, and run `manage.py shell`. So far I have: ``` ssh -i mysite.pem root@remotehost "cd /usr/local/myapp; /bin/bash -i -c \"python manage.py shell;\"" ``` This seems to work with the caveat that I can't see any ou...
Pass the `-t` option to `ssh`. > Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty. By default, running `ssh host command` ...
Display a decimal in scientific notation
6,913,532
34
2011-08-02T14:16:34Z
6,913,576
36
2011-08-02T14:19:57Z
[ "python", "string-formatting" ]
How can I display this: Decimal('40800000000.00000000000000') as '4.08E+10'? I've tried this: ``` >>> '%E' % Decimal('40800000000.00000000000000') '4.080000E+10' ``` But it has those extra 0's.
``` '%.2E' % Decimal('40800000000.00000000000000') # returns '4.08E+10' ``` In your '40800000000.00000000000000' there are many more significant zeros that have the same meaning as any other digit. That's why you have to tell explicitly where you want to stop. If you want to remove all trailing zeros automatically, ...
Display a decimal in scientific notation
6,913,532
34
2011-08-02T14:16:34Z
19,864,272
25
2013-11-08T16:44:41Z
[ "python", "string-formatting" ]
How can I display this: Decimal('40800000000.00000000000000') as '4.08E+10'? I've tried this: ``` >>> '%E' % Decimal('40800000000.00000000000000') '4.080000E+10' ``` But it has those extra 0's.
Here's an example using the `format()` function: ``` >>> "{:.2E}".format(Decimal('40800000000.00000000000000')) '4.08E+10' ``` * [official documentation](https://docs.python.org/3.3/library/string.html#formatspec) * [original format() proposal](http://www.python.org/dev/peps/pep-3101/)
Indexing python array with a python array with redundant elements
6,913,997
4
2011-08-02T14:50:36Z
6,914,184
7
2011-08-02T15:03:40Z
[ "python", "arrays", "indexing", "numpy", "scipy" ]
I'm experiencing a problem with array indexing. Suppose you have an array a and another array b you want to use to use as index for a in order to assign some values to the position pointed by b elements. ``` a=numpy.zeros(5) print a [ 0. 0. 0. 0. 0.] ``` Now I would like to increase the second element twice ```...
When you use an integer array for indexing another array, NumPy cannot create an adequate view, since the resulting array may not be representable with strides. Therefore, it will return a copy: ``` >>> a = np.zeros(5) >>> b = np.array([1, 1]) >>> c = a[b] >>> c array([ 0., 0.]) >>> c.base is a False ``` When using ...
Downloading files in twisted using queue
6,914,018
4
2011-08-02T14:51:42Z
6,914,573
8
2011-08-02T15:31:54Z
[ "python", "twisted" ]
I want to download a many files from queue using twisted and (for example ) 20 clients-threads. Any example ?
``` from twisted.internet.defer import inlineCallbacks, DeferredQueue @inlineCallbacks def worker(queue): while 1: url = yield queue.get() # wait for a url from the queue if url is None: # insert None into the queue to kill workers queue.put(None) return # done dat...
Django sending email
6,914,687
30
2011-08-02T15:39:23Z
6,915,291
67
2011-08-02T16:24:01Z
[ "python", "django", "smtp" ]
I know there are 20 questions similar to mine but I've tried for over a day now to get email to work with Django. I'm getting this error: `[Errno 111] Connection refused` when I attempt to send an email This is where I create the email and attempt to send it in my view: ``` try: msg = EmailMessage(subject, messa...
Are you trying to use a gmail account? Maybe try this then: ``` EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'your-username@gmail.com' EMAIL_HOST_PASSWORD = 'your-password' EMAIL_PORT = 587 EMAIL_USE_TLS = True ``` Then try test (django < 1.4) by ``` python manage.py shell >>> from django.core.mail import send_ma...
Django sending email
6,914,687
30
2011-08-02T15:39:23Z
11,590,015
16
2012-07-21T06:32:10Z
[ "python", "django", "smtp" ]
I know there are 20 questions similar to mine but I've tried for over a day now to get email to work with Django. I'm getting this error: `[Errno 111] Connection refused` when I attempt to send an email This is where I create the email and attempt to send it in my view: ``` try: msg = EmailMessage(subject, messa...
@mongoose\_za has a great answer, but the syntax is a bit different in Django 1.4+. Instead of: ``` send_mail('test email', 'hello world', to=['test@email.com']) ``` use ``` send_mail('test email', 'hello world', 'your@email.com', ['test@email.com']) ``` The first four arguments are required: subject, message, fro...
Django sending email
6,914,687
30
2011-08-02T15:39:23Z
23,402,208
31
2014-05-01T04:53:28Z
[ "python", "django", "smtp" ]
I know there are 20 questions similar to mine but I've tried for over a day now to get email to work with Django. I'm getting this error: `[Errno 111] Connection refused` when I attempt to send an email This is where I create the email and attempt to send it in my view: ``` try: msg = EmailMessage(subject, messa...
### First Create an Application specific password 1. Visit your [Google Account security page](https://www.google.com/settings/security). 2. In the `2-Step Verification` box, click `Settings`(if there is no settings link, you may want to create a new one. you can skip step 3 & 4). 3. Click the tab for `App-specific pa...
python iterator through tree with list of children
6,914,803
9
2011-08-02T15:47:54Z
6,915,269
16
2011-08-02T16:22:29Z
[ "python", "iterator" ]
i don't get the full grasp on python iterators, i got an object with a list of children, and i want to iterate through this structure. I want to get the same behaviour as with the printall function but with an iterator. ``` class t: def __init__(self, i): self.l = [] ...
It sounds like you want the iterator to act as a tree traversal. Study the `itertools` module and you can really go places. ``` from itertools import chain, imap class t: def __init__(self, value): self.value = value self.children = [] def __iter__(self): "implement the iterator protocol" for v in...
Is there a better solution for this ternary condition?
6,914,853
3
2011-08-02T15:51:45Z
6,914,872
7
2011-08-02T15:52:42Z
[ "python", "if-statement", "variable-assignment", "ternary" ]
Imagine the following ternary condition: ``` foreground = self.foreground if self.foreground else c4d.COLOR_TRANS ``` In this case, I need to call `self.foreground` twice just to check if it *is* `True` or not. Is there a way where I only need to call it once ?
An equivalent expression is ``` foreground = self.foreground or c4d.COLOR_TRANS ```
Saving a Numpy array as an image (instructions)
6,915,106
4
2011-08-02T16:10:59Z
6,917,185
16
2011-08-02T19:03:28Z
[ "python", "image", "numpy" ]
I found my answer in a previous post: [Saving a Numpy array as an image](http://stackoverflow.com/questions/902761/saving-a-numpy-array-as-an-image). The only problem being, there isn't much instruction on using the PyPNG module. There are only a few examples online-- <http://packages.python.org/pypng/ex.html#numpy> <...
You might be better off using PIL: ``` import Image import numpy as np data = np.random.random((100,100)) #Rescale to 0-255 and convert to uint8 rescaled = (255.0 / data.max() * (data - data.min())).astype(np.uint8) im = Image.fromarray(rescaled) im.save('test.png') ```
Simple IPC between C++ and Python (cross platform)
6,915,191
29
2011-08-02T16:17:15Z
6,915,636
31
2011-08-02T16:53:29Z
[ "c++", "python", "cross-platform", "ipc" ]
I have a C++ process running in the background that will be generating 'events' infrequently that a Python process running on the same box will need to pick up. * The code on the C side needs to be as lightweight as possible. * The Python side is read-only. * The implementation must be cross-platform. * The data being...
[zeromq](http://www.zeromq.org/) -- and nothing else. encode the messages as strings. However, If you want to get serialiazation from a library use [protobuf](http://code.google.com/p/protobuf/) it will generate classes for Python and C++. You use the SerializeToString() and ParseFromString() functions on either end, ...
GDAL install on Mac OS X Lion
6,915,700
9
2011-08-02T16:59:45Z
12,921,520
17
2012-10-16T18:51:50Z
[ "python", "osx-lion", "gdal" ]
I'm trying to install GDAL 1.7.1 on Mac OS X Lion using: ``` python setup.py build python setup.py install ``` and get the error: ``` running build running build_py running build_ext building 'osgeo._gdal' extension llvm-gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing ...
Homebrew works great for me. To install GDAL 1.9 with Homebrew all you have to do is ``` brew install gdal ``` Homebrew requires xcode, and I think commandline tools. More information can be found [here](https://speakerdeck.com/u/mikemcquaid/p/homebrew)
Is there a clean way to check if a given user exists on a computer through python?
6,916,208
2
2011-08-02T17:43:42Z
6,916,260
7
2011-08-02T17:46:48Z
[ "python", "operating-system", "pwd" ]
Currently I am using pwd.getpwall(), which shows me the entire password database. But I just want the users accounts of the computer. And with using getpwall() I am unable to do this ... ``` if 'foo' in pwd.getpwall(): do stuff ``` since pwd.getpwall() returns a list of objects. And if I wanted to check if a use...
In [the same page of the manual](http://docs.python.org/library/pwd.html#pwd.getpwnam): > ``` > pwd.getpwnam(name) > ``` > > Return the password database entry for the given user name. This is the result for an existent and an inexistent user: ``` >>> import pwd >>> pwd.getpwnam('root') pwd.struct_passwd(pw_name='ro...
Scientific computing in Python for MATLAB programmers
6,916,268
13
2011-08-02T17:47:09Z
6,916,282
11
2011-08-02T17:48:02Z
[ "python", "matlab", "scipy" ]
I was wondering if anybody knows of a good tutorial or introductory text on scientific computing on Python/SciPy for MATLAB programmers. I was thinking of something along the lines of [David Hiebeler's text](http://cran.r-project.org/doc/contrib/Hiebeler-matlabR.pdf) on [R](http://en.wikipedia.org/wiki/R_programming_l...
Take a look at <http://www.scipy.org/NumPy_for_Matlab_Users> You didn't ask for tools, but I thought I'd mention [Sage](http://www.sagemath.org/).
Writing List of Strings to Excel CSV File in Python
6,916,542
14
2011-08-02T18:08:34Z
6,916,576
30
2011-08-02T18:11:41Z
[ "python", "csv" ]
I am trying to create a csv file that contains the contents of a list of strings in Python, using the script below. However when I check my output file, it turns out that every character is delimited by a comma. How can I instruct the CSV.writer to delimit every individual string within the list rather than every chara...
The [`csv.writer`](http://docs.python.org/library/csv.html?highlight=csv#writer-objects) `writerow` method takes an iterable as argument. Your result set has to be a list (rows) of lists (columns). > ``` > csvwriter.writerow(row) > ``` > > Write the row parameter to the writer’s file object, formatted according to t...
Writing List of Strings to Excel CSV File in Python
6,916,542
14
2011-08-02T18:08:34Z
6,916,622
11
2011-08-02T18:15:54Z
[ "python", "csv" ]
I am trying to create a csv file that contains the contents of a list of strings in Python, using the script below. However when I check my output file, it turns out that every character is delimited by a comma. How can I instruct the CSV.writer to delimit every individual string within the list rather than every chara...
Very simple to fix, you just need to turn the parameter to writerow into a list. ``` for item in RESULTS: wr.writerow([item,]) ```
How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?
6,916,978
50
2011-08-02T18:45:27Z
6,917,046
30
2011-08-02T18:50:49Z
[ "python", "matplotlib", "plot", "figure" ]
I want to plot data, then create a new figure and plot data2, and finally come back to the original plot and plot data3, kinda like this: ``` import numpy as np import matplotlib as plt x = arange(5) y = np.exp(5) plt.figure() plt.plot(x, y) z = np.sin(x) plt.figure() plt.plot(x, z) w = np.cos(x) plt.figure("""firs...
When you call `figure`, simply number the plot. ``` x = arange(5) y = np.exp(5) plt.figure(0) plt.plot(x, y) z = np.sin(x) plt.figure(1) plt.plot(x, z) w = np.cos(x) plt.figure(0) # Here's the part I need plt.plot(x, w) ``` Edit: Note that you can number the plots however you want (here, starting from `0`) but if y...
How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?
6,916,978
50
2011-08-02T18:45:27Z
6,935,235
58
2011-08-04T01:40:38Z
[ "python", "matplotlib", "plot", "figure" ]
I want to plot data, then create a new figure and plot data2, and finally come back to the original plot and plot data3, kinda like this: ``` import numpy as np import matplotlib as plt x = arange(5) y = np.exp(5) plt.figure() plt.plot(x, y) z = np.sin(x) plt.figure() plt.plot(x, z) w = np.cos(x) plt.figure("""firs...
If you find yourself doing things like this regularly it may be worth investigating the object-oriented interface to matplotlib. In your case: ``` import matplotlib.pyplot as plt import numpy as np x = np.arange(5) y = np.exp(x) fig1 = plt.figure() ax1 = fig1.add_subplot(111) ax1.plot(x, y) z = np.sin(x) fig2 = plt....
In South, can I copy the value of an old column to a new one?
6,917,670
2
2011-08-02T19:44:38Z
6,918,002
11
2011-08-02T20:12:39Z
[ "python", "django", "django-models", "django-south" ]
One of my Django models is a subclass and I want to change its superclass to one that is very similar to the original one. In particular, the new superclass describes the same object and has the same primary key. How can I make South create the new OneToOne field and copy the values from the old one to the new one?
In south, there are two kinds of migrations: schema migrations and data migrations. After you've created the schemamigration, create a corresponding data migration: `./manage.py datamigration <app> <migration_name>` Do not run the migration (yet). Instead, open up the migration file you just created. You'll find th...
How do reimplement this Python XML-parsing function in Haskell?
6,918,069
4
2011-08-02T20:18:50Z
6,918,258
7
2011-08-02T20:35:40Z
[ "python", "xml", "haskell" ]
I recently wrote the following Python function which will take a Google Picasa contacts.xml file and output a dictionary with ID and Name. ``` def read_contacts_file(fn): import xml.etree.ElementTree x = xml.etree.ElementTree.ElementTree(file=fn) q = [(u.attrib["id"], u.attrib["name"]) for u in x.iter("con...
Here's a minimal example doing the same thing with [tagsoup](http://hackage.haskell.org/packages/archive/tagsoup/0.12.2/doc/html/Text-HTML-TagSoup.html): ``` import Text.HTML.TagSoup assocLookup k dict = [v | (k', v) <- dict, k == k'] readContactsFile fn = fmap parse (readFile fn) parse contents = do TagOpen "co...
Microsecond part lost when converting a date string to a datetime object in python
6,918,443
3
2011-08-02T20:49:41Z
6,918,527
7
2011-08-02T20:57:54Z
[ "python", "datetime", "time" ]
I have the following date string: ``` dtstr = '2010-12-19 03:44:34.778000' ``` I wanted to convert it to a datetime object, so i proceeded as follows: ``` import time from datetime import datetime dtstr = '2010-12-19 03:44:34.778000' format = "%Y-%m-%d %H:%M:%S.%f" datetime.fromtimestamp(time.mktime(time.strptime(d...
``` from datetime import datetime dtstr = '2010-12-19 03:44:34.778000' format = "%Y-%m-%d %H:%M:%S.%f" a = datetime.strptime(dtstr,format) print a.microsecond ``` `time` handles seconds since the Unix epoch, so using `time` loses the microseconds. Use `datetime.strptime` directly.
In python, why use logging instead of print?
6,918,493
19
2011-08-02T20:54:41Z
6,918,525
12
2011-08-02T20:57:35Z
[ "python", "logging", "printing" ]
For simple debugging in a complex project is there a reason to use the python logger instead of print? What about other use-cases? Is there an accepted best use-case for each (especially when you're only looking for stdout)? I've always heard that this is a "best practice" but I haven't been able to figure out why.
One of the biggest advantages of proper logging is that you can categorize messages and turn them on or off depending on what you need. For example, it might be useful to turn on debugging level messages for a certain part of the project, but tone it down for other parts, so as not to be taken over by information overl...
In python, why use logging instead of print?
6,918,493
19
2011-08-02T20:54:41Z
6,918,596
25
2011-08-02T21:03:40Z
[ "python", "logging", "printing" ]
For simple debugging in a complex project is there a reason to use the python logger instead of print? What about other use-cases? Is there an accepted best use-case for each (especially when you're only looking for stdout)? I've always heard that this is a "best practice" but I haven't been able to figure out why.
The logging package has a lot of useful features: * Easy to see where and when (even what line no.) a logging call is being made from. * You can log to files, sockets, pretty much anything, all at the same time. * You can differentiate your logging based on severity. Print doesn't have any of these. Also, if your pr...
How to pass arguments to a Button command in Tkinter?
6,920,302
51
2011-08-03T00:18:14Z
6,921,225
73
2011-08-03T03:07:50Z
[ "python", "python-3.x", "button", "tkinter", "arguments" ]
Suppose I have the following `Button` made with Tkinter in Python: ``` import Tkinter as Tk win = Tk.Toplevel() frame = Tk.Frame(master=win).grid(row=1, column=1) button = Tk.Button(master=frame, text='press', command=action) ``` The method `action` is called when I press the button, but what if I wanted to pass some...
I personally prefer to use `lambdas` in such a scenario, because imo it's clearer and simpler and also doesn't force you to write lots of wrapper methods if you don't have control over the called method, but that's certainly a matter of taste. That's how you'd do it with a lambda (note there's also some implementation...
How to pass arguments to a Button command in Tkinter?
6,920,302
51
2011-08-03T00:18:14Z
22,290,388
25
2014-03-10T00:57:19Z
[ "python", "python-3.x", "button", "tkinter", "arguments" ]
Suppose I have the following `Button` made with Tkinter in Python: ``` import Tkinter as Tk win = Tk.Toplevel() frame = Tk.Frame(master=win).grid(row=1, column=1) button = Tk.Button(master=frame, text='press', command=action) ``` The method `action` is called when I press the button, but what if I wanted to pass some...
This can also be done by using `partial` from the standard library [functools](http://docs.python.org/2/library/functools.html), like this: ``` from functools import partial #(...) action_with_arg = partial(action, arg) button = Tk.Button(master=frame, text='press', command=action_with_arg) ```
Python: Summing class instances inside a list
6,920,653
2
2011-08-03T01:19:14Z
6,920,662
7
2011-08-03T01:20:19Z
[ "python", "class", "list", "sum", "instances" ]
I am familiar with the built-in sum() function for lists and have used it before, eg: ``` sum(list1[0:41]) ``` when the list contains integers, but I'm in a situation where I have instances from a Class and I need them summed. I have this Class: ``` class DataPoint: def __init__(self, low, high, freq): ...
Have you tried: ``` sum(i.freq for i in items[0:41]) ``` If you need the cumulative sum of the last "i" elements, the following is the most efficient approach: ``` sums = [items[0].freq] for i in items[1:]: sums.append(sums[-1] + i.freq) ``` As other posters already have anticipated, it is a bad programming sty...
interprocess communication in python
6,920,858
19
2011-08-03T01:57:51Z
6,921,340
16
2011-08-03T03:31:58Z
[ "python", "sockets", "communication", "pipe", "interprocess" ]
What is a clean and elegant way to do interprocess communication between two different python processes? I currently use named pipes in the OS, but it feels a bit hacky. I rewrote my stuff with `dbus` services, which worked, but it seems when running the code remotely through an SSH session it now tries to initialise X...
Nah, [zeromq](http://zeromq.org) is the way to go. Delicious, isn't it? ``` import argparse import zmq parser = argparse.ArgumentParser(description='zeromq server/client') parser.add_argument('--bar') args = parser.parse_args() if args.bar: # client context = zmq.Context() socket = context.socket(zmq.REQ...
interprocess communication in python
6,920,858
19
2011-08-03T01:57:51Z
6,921,402
38
2011-08-03T03:44:44Z
[ "python", "sockets", "communication", "pipe", "interprocess" ]
What is a clean and elegant way to do interprocess communication between two different python processes? I currently use named pipes in the OS, but it feels a bit hacky. I rewrote my stuff with `dbus` services, which worked, but it seems when running the code remotely through an SSH session it now tries to initialise X...
The [`multiprocessing` library](http://docs.python.org/library/multiprocessing.html) provides [listeners and clients](http://docs.python.org/library/multiprocessing.html#multiprocessing-listeners-clients) that wrap sockets and allow you to pass arbitrary python objects. Your server could listen to receive python objec...
interprocess communication in python
6,920,858
19
2011-08-03T01:57:51Z
15,207,321
7
2013-03-04T17:24:50Z
[ "python", "sockets", "communication", "pipe", "interprocess" ]
What is a clean and elegant way to do interprocess communication between two different python processes? I currently use named pipes in the OS, but it feels a bit hacky. I rewrote my stuff with `dbus` services, which worked, but it seems when running the code remotely through an SSH session it now tries to initialise X...
From my experience, [`rpyc`](http://rpyc.readthedocs.org/en/latest/) is by far the simplest and most elegant way to go about it. (I know this is an old question, but I've just stumbled upon it..)