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 you split a list into evenly sized chunks?
312,443
959
2008-11-23T12:15:52Z
312,466
8
2008-11-23T12:40:39Z
[ "python", "list", "split", "chunks" ]
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially e...
If you know list size: ``` def SplitList(list, chunk_size): return [list[offs:offs+chunk_size] for offs in range(0, len(list), chunk_size)] ``` If you don't (an iterator): ``` def IterChunks(sequence, chunk_size): res = [] for item in sequence: res.append(item) if len(res) >= chunk_size: ...
How do you split a list into evenly sized chunks?
312,443
959
2008-11-23T12:15:52Z
312,467
56
2008-11-23T12:41:37Z
[ "python", "list", "split", "chunks" ]
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially e...
Here is a generator that work on arbitrary iterables: ``` def split_seq(iterable, size): it = iter(iterable) item = list(itertools.islice(it, size)) while item: yield item item = list(itertools.islice(it, size)) ``` Example: ``` >>> import pprint >>> pprint.pprint(list(split_seq(xrange(75...
How do you split a list into evenly sized chunks?
312,443
959
2008-11-23T12:15:52Z
312,644
204
2008-11-23T15:48:53Z
[ "python", "list", "split", "chunks" ]
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially e...
Directly from the (old) Python documentation (recipes for itertools): ``` from itertools import izip, chain, repeat def grouper(n, iterable, padvalue=None): "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')" return izip(*[chain(iterable, repeat(padvalue, n-1))]*n) ``` The current ve...
How do you split a list into evenly sized chunks?
312,443
959
2008-11-23T12:15:52Z
1,751,478
409
2009-11-17T20:17:16Z
[ "python", "list", "split", "chunks" ]
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially e...
If you want something super simple: ``` def chunks(l, n): n = max(1, n) return (l[i:i+n] for i in xrange(0, len(l), n)) ```
How do you split a list into evenly sized chunks?
312,443
959
2008-11-23T12:15:52Z
3,125,186
38
2010-06-26T19:10:07Z
[ "python", "list", "split", "chunks" ]
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially e...
``` def chunk(input, size): return map(None, *([iter(input)] * size)) ```
How do you split a list into evenly sized chunks?
312,443
959
2008-11-23T12:15:52Z
3,226,719
25
2010-07-12T07:58:43Z
[ "python", "list", "split", "chunks" ]
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially e...
Simple yet elegant ``` l = range(1, 1000) print [l[x:x+10] for x in xrange(0, len(l), 10)] ``` or if you prefer: ``` chunks = lambda l, n: [l[x: x+n] for x in xrange(0, len(l), n)] chunks(l, 10) ```
How do you split a list into evenly sized chunks?
312,443
959
2008-11-23T12:15:52Z
5,711,993
11
2011-04-19T05:27:19Z
[ "python", "list", "split", "chunks" ]
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially e...
If you had a chunk size of 3 for example, you could do: ``` zip(*[iterable[i::3] for i in range(3)]) ``` source: <http://code.activestate.com/recipes/303060-group-a-list-into-sequential-n-tuples/> I would use this when my chunk size is fixed number I can type, e.g. '3', and would never change.
How do you split a list into evenly sized chunks?
312,443
959
2008-11-23T12:15:52Z
16,004,505
8
2013-04-14T21:26:06Z
[ "python", "list", "split", "chunks" ]
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially e...
A generator expression: ``` def chunks(seq, n): return (seq[i:i+n] for i in xrange(0, len(seq), n)) ``` eg. ``` print list(chunks(range(1, 1000), 10)) ```
How do you split a list into evenly sized chunks?
312,443
959
2008-11-23T12:15:52Z
16,315,158
14
2013-05-01T08:42:21Z
[ "python", "list", "split", "chunks" ]
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially e...
[more-itertools has a chunks iterator.](http://pythonhosted.org/more-itertools/api.html#more_itertools.chunked) It also has a lot more things, including all the recipes in the itertools documentation.
How do you split a list into evenly sized chunks?
312,443
959
2008-11-23T12:15:52Z
16,935,535
35
2013-06-05T08:54:26Z
[ "python", "list", "split", "chunks" ]
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially e...
I know this is kind of old but I don't why nobody mentioned `numpy.array_split`: ``` lst = range(50) In [26]: np.array_split(b,5) Out[26]: [array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]), array([20, 21, 22, 23, 24, 25, 26, 27, 28, 29]), array([30, 31, 32, 33, 34, 35, 36, 37,...
How do you split a list into evenly sized chunks?
312,443
959
2008-11-23T12:15:52Z
19,264,525
11
2013-10-09T06:17:29Z
[ "python", "list", "split", "chunks" ]
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially e...
I like the Python doc's version proposed by tzot and J.F.Sebastian a lot, but it has two shortcomings: * it is not very explicit * I usually don't want a fill value in the last chunk I'm using this one a lot in my code: ``` from itertools import islice def chunks(n, iterable): iterable = iter(iterable) whil...
How do you split a list into evenly sized chunks?
312,443
959
2008-11-23T12:15:52Z
21,767,522
13
2014-02-13T23:07:17Z
[ "python", "list", "split", "chunks" ]
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially e...
## Critique of other answers here: None of these answers are evenly sized chunks, they all leave a runt chunk at the end, so they're not completely balanced. If you were using these functions to distribute work, you've built-in the prospect of one likely finishing well before the others, so it would sit around doing n...
How do you split a list into evenly sized chunks?
312,443
959
2008-11-23T12:15:52Z
22,045,226
29
2014-02-26T15:02:00Z
[ "python", "list", "split", "chunks" ]
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially e...
I'm surprised nobody has thought of using `iter`'s [two-argument form](http://docs.python.org/2/library/functions.html#iter): ``` from itertools import islice def chunk(it, size): it = iter(it) return iter(lambda: tuple(islice(it, size)), ()) ``` Demo: ``` >>> list(chunk(range(14), 3)) [(0, 1, 2), (3, 4, 5)...
How do you split a list into evenly sized chunks?
312,443
959
2008-11-23T12:15:52Z
29,009,933
18
2015-03-12T12:36:10Z
[ "python", "list", "split", "chunks" ]
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially e...
I saw the most awesome Python-ish answer in a [duplicate](http://stackoverflow.com/questions/23286254/convert-list-to-a-list-of-tuples-python) of this question: ``` l = range(1,15) i = iter(l) print zip(i,i,i) ``` You can create n-tuple for any n.
No Module named django.core
312,549
62
2008-11-23T14:09:24Z
325,295
34
2008-11-28T08:40:35Z
[ "python", "django" ]
I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this? ``` Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in <module> from django.core...
You must make sure that django is in your PYTHONPATH. To test, just do a `import django` from a python shell. There should be no output: ``` ActivePython 2.5.1.1 (ActiveState Software Inc.) based on Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credit...
No Module named django.core
312,549
62
2008-11-23T14:09:24Z
2,081,421
8
2010-01-17T15:21:48Z
[ "python", "django" ]
I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this? ``` Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in <module> from django.core...
I'm sure it's related to something incorrect in my setup, but I am having the same problem, and it works properly if I call it thusly ``` c:\somedir>python c:\Python26\scripts\django-admin.py startproject mysite ```
No Module named django.core
312,549
62
2008-11-23T14:09:24Z
2,172,329
18
2010-01-31T16:08:18Z
[ "python", "django" ]
I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this? ``` Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in <module> from django.core...
You can get around this problem by providing the full path to your django-admin.py file ``` python c:\python25\scripts\django-admin.py startproject mysite ```
No Module named django.core
312,549
62
2008-11-23T14:09:24Z
2,352,728
16
2010-02-28T21:21:39Z
[ "python", "django" ]
I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this? ``` Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in <module> from django.core...
I encountered this problem today, it turned out that I had C:\Python26 in my path and .py files were associated to Python 3.1. Repairing the proper version of Python, either through Programs and Features or by running the .msi, will fix the associations.
No Module named django.core
312,549
62
2008-11-23T14:09:24Z
8,186,132
9
2011-11-18T17:07:18Z
[ "python", "django" ]
I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this? ``` Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in <module> from django.core...
It was a PYTHONPATH environment variable issue for me, as others mentioned above, but noone has really shown how to set it for people that could use the extra instruction. **Linux (bash)** I set this variable in my bashrc file in my home folder (.bashrc is the file for me since my shell is /bin/bash). ``` vim ~/.bas...
No Module named django.core
312,549
62
2008-11-23T14:09:24Z
10,070,104
39
2012-04-09T07:13:06Z
[ "python", "django" ]
I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this? ``` Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in <module> from django.core...
I have the same problem on Windows and it seems I've found the problem. I have both 2.7 and 3.x installed. It seems it has something to do with the associate program of .py: In commandline type: > assoc .py and the result is: .py=Python.File which means .py is associated with Python.File then I tried this: > fty...
Python, optparse and file mask
312,673
3
2008-11-23T16:12:42Z
312,677
8
2008-11-23T16:20:25Z
[ "python", "optparse" ]
``` if __name__=='__main__': parser = OptionParser() parser.add_option("-i", "--input_file", dest="input_filename", help="Read input from FILE", metavar="FILE") (options, args) = parser.parse_args() print options ``` result is ``` $ python convert.py -i vide...
Python has nothing to do with this -- it's the shell. Call ``` $ python convert.py -i 'video_*' ``` and it will pass in that wildcard. The other six values were passed in as args, not attached to the `-i`, exactly as if you'd run `python convert.py -i video_1 video_2 video_3 video_4 video_5 video_6`, and the `-i` o...
Python: Problem with overloaded constructors
312,695
7
2008-11-23T16:41:56Z
312,727
36
2008-11-23T17:09:12Z
[ "python", "exception", "constructor-overloading" ]
WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions! I have written the following code, however I get the following exception: > Message File > Name Line Position Traceback Node > 31 > exceptions.TypeError: this constructor takes no arguments ``` class Computer: name...
I'm going to assume you're coming from a Java-ish background, so there are a few key differences to point out. ``` class Computer(object): """Docstrings are used kind of like Javadoc to document classes and members. They are the first thing inside a class or method. You probably want to extend object, to...
Django authentication and Ajax - URLs that require login
312,925
45
2008-11-23T20:35:16Z
523,196
50
2009-02-07T05:20:02Z
[ "javascript", "python", "django", "authentication" ]
I want to add some [Ajax](http://en.wikipedia.org/wiki/Ajax%5F%28programming%29)-niceness to my Django-coded website. In my Django code, I use the `@login_required` decorator from `django.contrib.auth.decorators` to mark which view requires authentication. The default behavior when a not authenticated user clicks it i...
I am facing the same issue, and, like you, I would like a simple decorator to wrap around a Django ajax view in order to handle authentication in the same way that I have other views. One approach that seems promising to me is to use such a decorator in conjunction with JavaScript that looks for a certain value in the ...
Comparing multiple dictionaries in Python
314,583
4
2008-11-24T16:02:37Z
314,633
7
2008-11-24T16:16:20Z
[ "python", "data-mining" ]
I'm new to Python and am running to a problem I can't google my way out of. I've built a GUI using wxPython and ObjectiveListView. In its very center, the GUI has a list control displaying data in X rows (the data is loaded by the user) and in five columns. When the user selects multiple entries from the list control ...
``` >>> mysets = (set(x.items()) for x in MyList) >>> reduce(lambda a,b: a.intersection(b), mysets) set([('sum', '-21,90'), ('type', 'Purchase'), ('target', 'Apple Store')]) ``` First, I've created a generator that will convert the list of dicts into an iterable sequence of sets of key,value pairs. You could use a lis...
How to debug Web2py applications?
315,165
16
2008-11-24T19:27:05Z
315,318
8
2008-11-24T20:22:22Z
[ "python", "debugging", "web2py" ]
Is it possible? By debug I mean setting breakpoints, inspect values and advance step by step.
I haven't used web2py, but if it runs in a terminal window, you can use standard pdb stuff. Add this line somewhere in your code: ``` import pdb; pdb.set_trace() ``` This will invoke the debugger and break. Then you can use [PDB](http://docs.python.org/lib/module-pdb.html) commands: n to step to the next line, l to l...
How to debug Web2py applications?
315,165
16
2008-11-24T19:27:05Z
318,501
9
2008-11-25T19:03:51Z
[ "python", "debugging", "web2py" ]
Is it possible? By debug I mean setting breakpoints, inspect values and advance step by step.
You can do remote debugging of python web apps over TCP/IP with [winpdb](http://winpdb.org/).
How to debug Web2py applications?
315,165
16
2008-11-24T19:27:05Z
806,233
8
2009-04-30T10:04:10Z
[ "python", "debugging", "web2py" ]
Is it possible? By debug I mean setting breakpoints, inspect values and advance step by step.
One can debug applications built on Web2py using the following set-up: 1. Eclipse IDE 2. Install Pydev into Eclipse 3. Set Breakpoints on your code as needed 4. Within Eclipse right-click the file web2py.py and select Debug As -> Python Run 5. When a breakpoint is hit Eclipse will jump to the breakpoint where you can ...
Properly formatted example for Python iMAP email access?
315,362
9
2008-11-24T20:31:14Z
315,710
10
2008-11-24T22:18:52Z
[ "python", "email", "imap" ]
tldr: Can someone show me how to properly format this Python iMAP example so it works? from <https://docs.python.org/2.4/lib/imap4-example.html> > ``` > import getpass, imaplib > > M = imaplib.IMAP4() > M.login(getpass.getuser(), getpass.getpass()) > M.select() > typ, data = M.search(None, 'ALL') > for num in data[0]...
``` import imaplib # you want to connect to a server; specify which server server= imaplib.IMAP4_SSL('imap.googlemail.com') # after connecting, tell the server who you are server.login('email@gmail.com', 'password') # this will show you a list of available folders # possibly your Inbox is called INBOX, but check the l...
Properly formatted example for Python iMAP email access?
315,362
9
2008-11-24T20:31:14Z
316,457
10
2008-11-25T05:42:27Z
[ "python", "email", "imap" ]
tldr: Can someone show me how to properly format this Python iMAP example so it works? from <https://docs.python.org/2.4/lib/imap4-example.html> > ``` > import getpass, imaplib > > M = imaplib.IMAP4() > M.login(getpass.getuser(), getpass.getpass()) > M.select() > typ, data = M.search(None, 'ALL') > for num in data[0]...
Here is a script I used to use to grab logwatch info from my mailbox. [Presented at LFNW 2008](http://brianlane.com/articles/lfnw2008/) - ``` #!/usr/bin/env python ''' Utility to scan my mailbox for new mesages from Logwatch on systems and then grab useful info from the message and output a summary page. by ...
How do I search through a folder for the filename that matches a regular expression using Python?
315,381
2
2008-11-24T20:38:45Z
315,430
8
2008-11-24T20:51:04Z
[ "python", "regex" ]
I am having some difficulty writing a function that will search through a directory for a file that matches a specific regular expression (which I have compiled using 're.compile'). So my question is: How do I search through a directory (I plan to use os.walk) for a file that matches a specific regular expression? An e...
This will find all files starting with two digits and ending in gif, you can add the files into a global list, if you wish: ``` import re import os r = re.compile(r'\d{2}.+gif$') for root, dirs, files in os.walk('/home/vinko'): l = [os.path.join(root,x) for x in files if r.match(x)] if l: print l #Or append to a g...
Automagically expanding a Python list with formatted output
315,672
6
2008-11-24T22:02:29Z
315,684
16
2008-11-24T22:06:59Z
[ "python", "list", "mysql" ]
Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values. For instance, in the code below, I'd like to have the numeric val...
try: ``` ",".join( map(str, record_ids) ) ``` `",".join( list_of_strings )` joins a list of string by separating them with commas if you have a list of numbers, `map( str, list )` will convert it to a list of strings
Running a function periodically in twisted protocol
315,716
23
2008-11-24T22:21:17Z
316,559
36
2008-11-25T07:12:05Z
[ "python", "tcp", "twisted", "protocols" ]
I am looking for a way to periodically send some data over all clients connected to a TCP port. I am looking at twisted python and I am aware of reactor.callLater. But how do I use it to send some data to all connected clients periodically ? The data sending logic is in Protocol class and it is instantiated by the reac...
You would probably want to do this in the Factory for the connections. The Factory is not automatically notified of every time a connection is made and lost, so you can notify it from the Protocol. Here is a complete example of how to use twisted.internet.task.LoopingCall in conjunction with a customised basic Factory...
Python float to Decimal conversion
316,238
26
2008-11-25T02:53:44Z
316,253
25
2008-11-25T03:07:03Z
[ "python", "decimal" ]
Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first. This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if you have a number that could have as man...
### Python <2.7 ``` "%.15g" % f ``` Or in Python 3.0: ``` format(f, ".15g") ``` ### Python 2.7+, 3.2+ Just pass the float to `Decimal` constructor directly.
Python float to Decimal conversion
316,238
26
2008-11-25T02:53:44Z
316,308
21
2008-11-25T03:40:02Z
[ "python", "decimal" ]
Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first. This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if you have a number that could have as man...
You said in your question: > Can someone suggest a good way to > convert from float to Decimal > **preserving value as the user has > entered** But every time the user enters a value, it is entered as a string, not as a float. You are converting it to a float somewhere. Convert it to a Decimal directly instead and no...
Problem compiling MySQLdb for Python 2.6 on Win32
316,484
9
2008-11-25T06:14:20Z
319,007
9
2008-11-25T21:51:20Z
[ "python", "mysql", "winapi" ]
I'm using Django and Python 2.6, and I want to grow my application using a MySQL backend. Problem is that there isn't a win32 package for MySQLdb on Python 2.6. Now I'm no hacker, but I thought I might compile it myself using MSVC++9 Express. But I run into a problem that the compiler quickly can't find `config_win.h`...
Thanks all! I found that I hadn't installed the developer components in MySQL. Once that was done the problem was solved and I easily compiled the MySQLdb for Python 2.6. I've made the package available at [my site](http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe).
Ping a site in Python?
316,866
64
2008-11-25T09:58:37Z
316,974
35
2008-11-25T10:49:58Z
[ "python", "network-programming", "ping" ]
The basic code is: ``` from Tkinter import * import os,sys ana= Tk() def ping1(): os.system('ping') a=Button(pen) ip=("192.168.0.1") a.config(text="PING",bg="white",fg="blue") a=ping1.ip ??? a.pack() ana.mainloop() ``` How could I ping a sites or address?
Depending on what you want to achive, you are probably easiest calling the system ping command.. Using the subprocess module is the best way of doing this, although you have to remember the ping command is different on different operating systems! ``` import subprocess host = "www.google.com" ping = subprocess.Pope...
Ping a site in Python?
316,866
64
2008-11-25T09:58:37Z
317,021
9
2008-11-25T11:12:56Z
[ "python", "network-programming", "ping" ]
The basic code is: ``` from Tkinter import * import os,sys ana= Tk() def ping1(): os.system('ping') a=Button(pen) ip=("192.168.0.1") a.config(text="PING",bg="white",fg="blue") a=ping1.ip ??? a.pack() ana.mainloop() ``` How could I ping a sites or address?
It's hard to say what your question is, but there are some alternatives. If you mean to literally execute a request using the ICMP ping protocol, you can get an ICMP library and execute the ping request directly. Google "Python ICMP" to find things like this [icmplib](http://code.activestate.com/recipes/409689/). You ...
Ping a site in Python?
316,866
64
2008-11-25T09:58:37Z
317,172
37
2008-11-25T12:28:42Z
[ "python", "network-programming", "ping" ]
The basic code is: ``` from Tkinter import * import os,sys ana= Tk() def ping1(): os.system('ping') a=Button(pen) ip=("192.168.0.1") a.config(text="PING",bg="white",fg="blue") a=ping1.ip ??? a.pack() ana.mainloop() ``` How could I ping a sites or address?
You may find [Noah Gift's](http://noahgift.com/) presentation [Creating Agile Commandline Tools With Python](http://www.slideshare.net/noahgift/pycon2008-cli-noahgift). In it he combines subprocess, Queue and threading to develop solution that is capable of pinging hosts concurrently and speeding up the process. Below ...
Ping a site in Python?
316,866
64
2008-11-25T09:58:37Z
317,206
76
2008-11-25T12:39:12Z
[ "python", "network-programming", "ping" ]
The basic code is: ``` from Tkinter import * import os,sys ana= Tk() def ping1(): os.system('ping') a=Button(pen) ip=("192.168.0.1") a.config(text="PING",bg="white",fg="blue") a=ping1.ip ??? a.pack() ana.mainloop() ``` How could I ping a sites or address?
See this [pure Python ping](https://pypi.python.org/pypi/python-ping/2011.10.17.376a019) by [Matthew Dixon Cowles](http://www.mondoinfo.com/) and [Jens Diemer](http://www.jensdiemer.de/). Also, remember that Python requires root to spawn ICMP (i.e. ping) sockets in linux. ``` import ping, socket try: ping.verbose_...
Ping a site in Python?
316,866
64
2008-11-25T09:58:37Z
1,165,094
7
2009-07-22T12:59:52Z
[ "python", "network-programming", "ping" ]
The basic code is: ``` from Tkinter import * import os,sys ana= Tk() def ping1(): os.system('ping') a=Button(pen) ip=("192.168.0.1") a.config(text="PING",bg="white",fg="blue") a=ping1.ip ??? a.pack() ana.mainloop() ``` How could I ping a sites or address?
I did something similar this way, as an inspiration: ``` import urllib import threading import time def pinger_urllib(host): """ helper function timing the retrival of index.html TODO: should there be a 1MB bogus file? """ t1 = time.time() urllib.urlopen(host + '/index.html').read() return (time.time()...
Get Element value with minidom with Python
317,413
78
2008-11-25T13:57:02Z
317,421
100
2008-11-25T13:59:13Z
[ "python", "dom", "minidom" ]
I am creating a GUI frontend for the Eve Online API in Python. I have successfully pulled the XML data from their server. I am trying to grab the value from a node called "name": ``` from xml.dom.minidom import parse dom = parse("C:\\eve.xml") name = dom.getElementsByTagName('name') print name ``` This seems to fin...
It should just be ``` name[0].firstChild.nodeValue ```
Get Element value with minidom with Python
317,413
78
2008-11-25T13:57:02Z
317,494
50
2008-11-25T14:21:08Z
[ "python", "dom", "minidom" ]
I am creating a GUI frontend for the Eve Online API in Python. I have successfully pulled the XML data from their server. I am trying to grab the value from a node called "name": ``` from xml.dom.minidom import parse dom = parse("C:\\eve.xml") name = dom.getElementsByTagName('name') print name ``` This seems to fin...
Probably something like this if it's the text part you want... ``` from xml.dom.minidom import parse dom = parse("C:\\eve.xml") name = dom.getElementsByTagName('name') print " ".join(t.nodeValue for t in name[0].childNodes if t.nodeType == t.TEXT_NODE) ``` The text part of a node is considered a node in itself place...
Get Element value with minidom with Python
317,413
78
2008-11-25T13:57:02Z
4,835,703
10
2011-01-29T07:28:23Z
[ "python", "dom", "minidom" ]
I am creating a GUI frontend for the Eve Online API in Python. I have successfully pulled the XML data from their server. I am trying to grab the value from a node called "name": ``` from xml.dom.minidom import parse dom = parse("C:\\eve.xml") name = dom.getElementsByTagName('name') print name ``` This seems to fin...
you can use something like this.It worked out for me ``` doc = parse('C:\\eve.xml') my_node_list = doc.getElementsByTagName("name") my_n_node = my_node_list[0] my_child = my_n_node.firstChild my_text = my_child.data print my_text ```
Standard C or Python libraries to compute standard deviation of normal distribution
317,963
4
2008-11-25T16:25:34Z
318,986
7
2008-11-25T21:44:54Z
[ "python", "c", "algorithm", "math", "probability" ]
Say we have normal distribution n(x): mean=0 and \int\_{-a}^{a} n(x) = P. What is the easiest way to compute standard deviation of such distribution? May be there are standard libraries for python or C, that are suitable for that task?
If X is normal with mean 0 and standard deviation sigma, it must hold ``` P = Prob[ -a <= X <= a ] = Prob[ -a/sigma <= N <= a/sigma ] = 2 Prob[ 0 <= N <= a/sigma ] = 2 ( Prob[ N <= a/sigma ] - 1/2 ) ``` where N is normal with mean 0 and standard deviation 1. Hence ``` P/2 + 1/2 = Prob[ N <= a/sigma ] = Phi(a/sig...
Python: converting strings for use with ctypes.c_void_p()
318,067
7
2008-11-25T16:49:18Z
318,140
10
2008-11-25T17:12:04Z
[ "python", "dll", "types", "ctypes" ]
given a string: ``` msg="hello world" ``` **How can I define this as a `ctypes.c_void_p()` data type?** the following code yields a "cannot be converted to pointer" exception: ``` data=ctypes.c_void_p(msg) ``` `data` is required to be a `void*` type in C, because it is being passed to a DLL. I'm assuming there is...
Something like this? Using `ctypes.cast`? ``` >>> import ctypes >>> p1= ctypes.c_char_p("hi mom") >>> ctypes.cast( p1, ctypes.c_void_p ) c_void_p(11133300) ```
How do I do a case insensitive string comparison in Python?
319,426
270
2008-11-26T01:06:44Z
319,435
288
2008-11-26T01:09:22Z
[ "python", "comparison", "case-insensitive" ]
What's the best way to do case insensitive string comparison in Python? I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged ...
Assuming ASCII strings: ``` string1 = 'Hello' string2 = 'hello' if string1.lower() == string2.lower(): print "The strings are the same (case insensitive)" else: print "The strings are not the same (case insensitive)" ```
How do I do a case insensitive string comparison in Python?
319,426
270
2008-11-26T01:06:44Z
11,573,384
43
2012-07-20T05:27:24Z
[ "python", "comparison", "case-insensitive" ]
What's the best way to do case insensitive string comparison in Python? I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged ...
Using Python 2, calling `.lower()` on each string or Unicode object... ``` string1.lower() == string2.lower() ``` ...will work most of the time, but indeed doesn't work in the situations @tchrist has described. Assume we have a file called `unicode.txt` containing the two strings `Σίσυφος` and `ΣΊΣΥΦΟΣ...
How do I do a case insensitive string comparison in Python?
319,426
270
2008-11-26T01:06:44Z
29,247,821
164
2015-03-25T05:01:44Z
[ "python", "comparison", "case-insensitive" ]
What's the best way to do case insensitive string comparison in Python? I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged ...
Comparing string in a case insensitive way seems like something that's trivial, but it's not. I will be using Python 3, since Python 2 is underdeveloped here. The first thing to note it that case-removing conversions in unicode aren't trivial. There is text for which `text.lower() != text.upper().lower()`, such as `"Ã...
How to upload a file with django (python) and s3?
319,923
11
2008-11-26T06:39:33Z
319,943
18
2008-11-26T06:57:11Z
[ "python", "django", "file-upload", "amazon-s3" ]
I'm looking for a way to upload a file to s3. I am using django. I am currently using amazon's python library for uploading along with the following code: View: ``` def submitpicture(request): fuser = request.session["login"] copied_data = request.POST.copy() copied_data.update(request.FILES) content...
You will have to provide the enctype attribute to the FORM element (I've been bitten by this before). For example, your FORM tag should look like: ``` <form action="/submitpicture/" method="POST" enctype="multipart/form-data" > ``` Without the enctype, you will find yourself with an empty request.FILES.
Ensuring subprocesses are dead on exiting Python program
320,232
36
2008-11-26T10:21:21Z
320,290
13
2008-11-26T10:56:21Z
[ "python", "subprocess", "kill", "zombie-process" ]
Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen(). If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?
The `subprocess.Popen.wait()` is the only way to assure that they're dead. Indeed, POSIX OS's require that you wait on your children. Many \*nix's will create a "zombie" process: a dead child for which the parent didn't wait. If the child is reasonably well-written, it terminates. Often, children read from PIPE's. Clo...
Ensuring subprocesses are dead on exiting Python program
320,232
36
2008-11-26T10:21:21Z
320,712
29
2008-11-26T13:36:39Z
[ "python", "subprocess", "kill", "zombie-process" ]
Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen(). If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?
You can use [**atexit**](http://docs.python.org/library/atexit.html) for this, and register any clean up tasks to be run when your program exits. **atexit.register(func[, \*args[, \*\*kargs]])** In your cleanup process, you can also implement your own wait, and kill it when a your desired timeout occurs. ``` >>> imp...
Ensuring subprocesses are dead on exiting Python program
320,232
36
2008-11-26T10:21:21Z
322,317
21
2008-11-26T22:02:49Z
[ "python", "subprocess", "kill", "zombie-process" ]
Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen(). If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?
On \*nix's, maybe using process groups can help you out - you can catch subprocesses spawned by your subprocesses as well. ``` if __name__ == "__main__": os.setpgrp() # create new process group, become its leader try: # some code finally: os.killpg(0, signal.SIGKILL) # kill all processes in my group ``` ...
Currency formatting in Python
320,929
99
2008-11-26T14:43:33Z
320,951
133
2008-11-26T14:50:59Z
[ "python", "formatting", "currency" ]
I am looking to format a number like 188518982.18 to £188,518,982.18 using Python. How can I do this?
See the [locale](https://docs.python.org/2/library/locale.html) module. This does currency (and date) formatting. ``` >>> import locale >>> locale.setlocale( locale.LC_ALL, '' ) 'English_United States.1252' >>> locale.currency( 188518982.18 ) '$188518982.18' >>> locale.currency( 188518982.18, grouping=True ) '$188,51...
Currency formatting in Python
320,929
99
2008-11-26T14:43:33Z
1,082,547
15
2009-07-04T16:41:31Z
[ "python", "formatting", "currency" ]
I am looking to format a number like 188518982.18 to £188,518,982.18 using Python. How can I do this?
My locale settings seemed incomplete, so I had too look beyond this SO answer and found: <http://docs.python.org/library/decimal.html#recipes> OS-independent Just wanted to share here.
Currency formatting in Python
320,929
99
2008-11-26T14:43:33Z
3,393,776
63
2010-08-03T05:20:21Z
[ "python", "formatting", "currency" ]
I am looking to format a number like 188518982.18 to £188,518,982.18 using Python. How can I do this?
## New in 2.7 ``` >>> '{:20,.2f}'.format(18446744073709551616.0) '18,446,744,073,709,551,616.00' ``` <http://docs.python.org/dev/whatsnew/2.7.html#pep-0378>
Currency formatting in Python
320,929
99
2008-11-26T14:43:33Z
3,866,014
8
2010-10-05T17:08:55Z
[ "python", "formatting", "currency" ]
I am looking to format a number like 188518982.18 to £188,518,982.18 using Python. How can I do this?
If you are using OSX and have yet to set your locale module setting this first answer will not work you will receive the following error: ``` Traceback (most recent call last):File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py", line 221, in curre...
Currency formatting in Python
320,929
99
2008-11-26T14:43:33Z
8,851,191
28
2012-01-13T13:17:00Z
[ "python", "formatting", "currency" ]
I am looking to format a number like 188518982.18 to £188,518,982.18 using Python. How can I do this?
Not quite sure why it's not mentioned more online (or on this thread), but the [Babel](http://babel.pocoo.org/) package (and Django utilities) from the Edgewall guys is awesome for currency formatting (and lots of other i18n tasks). It's nice because it doesn't suffer from the need to do everything globally like the co...
Making functions non override-able
321,024
5
2008-11-26T15:08:29Z
321,119
9
2008-11-26T15:34:24Z
[ "python" ]
I know python functions are virtual by default. Let's say I have this: ``` class Foo: def __init__(self, args): do some stuff def goo(): print "You can overload me" def roo(): print "You cannot overload me" ``` I don't want them to be able to do this: ``` class Aoo(Foo): def r...
Since Python has monkey patching, not only can you not make anything "private". Even if you could, someone could still monkeypatch in a new version of the method function. You can use this kind of name as a "don't go near" warning. ``` class Foo( object ): def _roo( self ): """Change this at your own risk....
Making functions non override-able
321,024
5
2008-11-26T15:08:29Z
321,240
26
2008-11-26T16:07:04Z
[ "python" ]
I know python functions are virtual by default. Let's say I have this: ``` class Foo: def __init__(self, args): do some stuff def goo(): print "You can overload me" def roo(): print "You cannot overload me" ``` I don't want them to be able to do this: ``` class Aoo(Foo): def r...
You can use a metaclass: ``` class NonOverridable(type): def __new__(self, name, bases, dct): if bases and "roo" in dct: raise SyntaxError, "Overriding roo is not allowed" return type.__new__(self, name, bases, dct) class foo: __metaclass__=NonOverridable ... ``` The metatype'...
Comparing XML in a unit test in Python
321,795
30
2008-11-26T19:09:08Z
321,893
13
2008-11-26T19:35:15Z
[ "python", "xml", "elementtree" ]
I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in ...
First normalize 2 XML, then you can compare them. I've used the following using lxml ``` obj1 = objectify.fromstring(expect) expect = etree.tostring(obj1) obj2 = objectify.fromstring(xml) result = etree.tostring(obj2) self.assertEquals(expect, result) ```
Comparing XML in a unit test in Python
321,795
30
2008-11-26T19:09:08Z
321,941
7
2008-11-26T19:56:19Z
[ "python", "xml", "elementtree" ]
I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in ...
If the problem is really just the whitespace and attribute order, and you have no other constructs than text and elements to worry about, you can parse the strings using a standard XML parser and compare the nodes manually. Here's an example using minidom, but you could write the same in etree pretty simply: ``` def i...
Comparing XML in a unit test in Python
321,795
30
2008-11-26T19:09:08Z
7,060,342
15
2011-08-14T23:05:34Z
[ "python", "xml", "elementtree" ]
I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in ...
This is an old question, but the accepted Kozyarchuk's answer doesn't work for me because of attributes order, and the minidom solution doesn't work as-is either (no idea why, I haven't debugged it). This is what I finally came up with: ``` from doctest import Example from lxml.doctestcompare import LXMLOutputChecker...
Does c# have anything comparable to Python's list comprehensions
323,032
12
2008-11-27T05:55:24Z
323,039
16
2008-11-27T05:59:36Z
[ "c#", "python", "list" ]
I want to generate a list in C#. I am missing python's list comprehensions. Is there a c# way to create collections on the fly like list comprehensions or generator statements do in python?
If you are using C# 3.0 (VS2008) then LINQ to Objects can do very similar things: ``` List<Foo> fooList = new List<Foo>(); IEnumerable<Foo> extract = from foo in fooList where foo.Bar > 10 select Foo.Name.ToUpper(); ```
Does c# have anything comparable to Python's list comprehensions
323,032
12
2008-11-27T05:55:24Z
323,058
13
2008-11-27T06:24:33Z
[ "c#", "python", "list" ]
I want to generate a list in C#. I am missing python's list comprehensions. Is there a c# way to create collections on the fly like list comprehensions or generator statements do in python?
Matt has mentioned query expressions. These are available for LINQ in general, by the way - not just LINQ to Objects. (For example, the same query applied to a LINQ to SQL datacontext would execute the filter and projection on the database.) The query expressions in C# 3 are simply syntactic sugar over writing normal ...
py2exe fails to generate an executable
323,424
48
2008-11-27T10:31:51Z
325,456
35
2008-11-28T10:36:56Z
[ "python", "wxpython", "py2exe" ]
I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. My setup.py looks like this: ``` from distutil...
I've discovered that py2exe works just fine if I comment out the part of my program that uses wxPython. Also, when I use py2exe on the 'simple' sample that comes with its download (i.e. in Python26\Lib\site-packages\py2exe\samples\simple), I get this error message: ``` *** finding dlls needed *** error: MSVCP90.dll: N...
py2exe fails to generate an executable
323,424
48
2008-11-27T10:31:51Z
774,715
37
2009-04-21T21:29:58Z
[ "python", "wxpython", "py2exe" ]
I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. My setup.py looks like this: ``` from distutil...
I put this in all my setup.py scripts: ``` distutils.core.setup( options = { "py2exe": { "dll_excludes": ["MSVCP90.dll"] } }, ... ) ``` This keeps py2exe quiet, but you still need to make sure that dll is on the user's machine.
py2exe fails to generate an executable
323,424
48
2008-11-27T10:31:51Z
4,216,212
10
2010-11-18T15:07:21Z
[ "python", "wxpython", "py2exe" ]
I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. My setup.py looks like this: ``` from distutil...
wxPython has nothing to do with it. Before Python 2.6, Python used Visual Studio 2003 as their Windows compiler. Beginning with 2.6, they switched to Visual Studio 2008, which requires a manifest file in some situations. This has been well documented. See the following links: <http://wiki.wxpython.org/py2exe> <http:/...
How to get the name of an open file?
323,515
13
2008-11-27T11:28:25Z
323,522
33
2008-11-27T11:30:31Z
[ "python", "file" ]
I'm trying to store in a variable the name of the current file that I've opened from a folder... How can I do that? I've tried cwd = os.getcwd() but this only gives me the path of the folder, and I need to store the name of the opened file... Can you please help me? Thanks.
``` Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('generic.png','r') >>> f.name 'generic.png' ```
How to get the name of an open file?
323,515
13
2008-11-27T11:28:25Z
24,144,992
13
2014-06-10T15:30:11Z
[ "python", "file" ]
I'm trying to store in a variable the name of the current file that I've opened from a folder... How can I do that? I've tried cwd = os.getcwd() but this only gives me the path of the folder, and I need to store the name of the opened file... Can you please help me? Thanks.
One more useful trick to add. I agree with original correct answer, however if you're like me came to this page wanting the filename only without the rest of the path, this works well. ``` >>> f = open('/tmp/generic.png','r') >>> f.name '/tmp/generic.png' >>> import os >>> os.path.basename(f.name) 'generic.png' ```
Python list slice syntax used for no obvious reason
323,689
31
2008-11-27T12:57:05Z
323,698
48
2008-11-27T13:00:31Z
[ "python", "list", "shallow-copy" ]
I occasionally see the list slice syntax used in Python code like this: ``` newList = oldList[:] ``` Surely this is just the same as: ``` newList = oldList ``` Or am I missing something?
`[:]` [Shallow copies](http://en.wikipedia.org/wiki/Deep_copy#Shallow_copy) the list, making a copy of the list structure containing references to the original list members. This means that operations on the copy do not affect the structure of the original. However, if you do something to the list members, both lists s...
Python list slice syntax used for no obvious reason
323,689
31
2008-11-27T12:57:05Z
323,733
44
2008-11-27T13:13:58Z
[ "python", "list", "shallow-copy" ]
I occasionally see the list slice syntax used in Python code like this: ``` newList = oldList[:] ``` Surely this is just the same as: ``` newList = oldList ``` Or am I missing something?
Like NXC said, Python variable names actually point to an object, and not a specific spot in memory. `newList = oldList` would create two different variables that point to the same object, therefore, changing `oldList` would also change `newList`. However, when you do `newList = oldList[:]`, it "slices" the list, and...
Python list slice syntax used for no obvious reason
323,689
31
2008-11-27T12:57:05Z
323,800
10
2008-11-27T13:40:50Z
[ "python", "list", "shallow-copy" ]
I occasionally see the list slice syntax used in Python code like this: ``` newList = oldList[:] ``` Surely this is just the same as: ``` newList = oldList ``` Or am I missing something?
As it has already been answered, I'll simply add a simple demonstration: ``` >>> a = [1, 2, 3, 4] >>> b = a >>> c = a[:] >>> b[2] = 10 >>> c[3] = 20 >>> a [1, 2, 10, 4] >>> b [1, 2, 10, 4] >>> c [1, 2, 3, 20] ```
How to access previous/next element while for looping?
323,750
31
2008-11-27T13:22:19Z
323,910
52
2008-11-27T14:28:23Z
[ "python" ]
Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop? ``` l=[1,2,3] for item in l: if item==2: get_previous(l,item) ```
Expressed as a generator function: ``` def neighborhood(iterable): iterator = iter(iterable) prev = None item = iterator.next() # throws StopIteration if empty. for next in iterator: yield (prev,item,next) prev = item item = next yield (prev,item,None) ``` Usage: ``` for ...
How to access previous/next element while for looping?
323,750
31
2008-11-27T13:22:19Z
324,273
7
2008-11-27T17:15:38Z
[ "python" ]
Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop? ``` l=[1,2,3] for item in l: if item==2: get_previous(l,item) ```
``` l=[1,2,3] for i,item in enumerate(l): if item==2: get_previous=l[i-1] print get_previous >>>1 ```
How to access previous/next element while for looping?
323,750
31
2008-11-27T13:22:19Z
23,531,068
11
2014-05-08T01:10:28Z
[ "python" ]
Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop? ``` l=[1,2,3] for item in l: if item==2: get_previous(l,item) ```
One simple way. ``` l=[1,2,3] for i,j in zip(l, l[1:]): print i, j ```
Foreign key from one app into another in Django
323,763
49
2008-11-27T13:24:45Z
323,905
79
2008-11-27T14:27:45Z
[ "python", "django", "django-models" ]
I'm wondering if it's possible to define a foreign key in a models.py file in Django that is a reference to a table in another app? In other words, I have two apps, called cf and profiles, and in cf/models.py I have (amongst other things): ``` class Movie(models.Model): title = models.CharField(max_length=255) ``...
According to the docs, your second attempt should work: > To refer to models defined in another application, you must instead explicitly specify the application label. For example, if the Manufacturer model above is defined in another application called production, you'd need to use: ``` class Car(models.Model): ...
Foreign key from one app into another in Django
323,763
49
2008-11-27T13:24:45Z
32,869,639
12
2015-09-30T15:09:36Z
[ "python", "django", "django-models" ]
I'm wondering if it's possible to define a foreign key in a models.py file in Django that is a reference to a table in another app? In other words, I have two apps, called cf and profiles, and in cf/models.py I have (amongst other things): ``` class Movie(models.Model): title = models.CharField(max_length=255) ``...
It is also possible to pass the class itself: ``` from django.db import models from production import models as production_models class Car(models.Model): manufacturer = models.ForeignKey(production_models.Manufacturer) ```
Is there any way to kill a Thread in Python?
323,972
399
2008-11-27T14:55:53Z
323,981
25
2008-11-27T14:58:49Z
[ "python", "multithreading", "kill", "terminate" ]
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
You should never forcibly kill a thread without cooperating with it. Killing a thread removes any guarantees that try/finally blocks set up so you might leave locks locked, files open, etc. The only time you can argue that forcibly killing threads is a good idea is to kill a program fast, but never single threads.
Is there any way to kill a Thread in Python?
323,972
399
2008-11-27T14:55:53Z
323,993
89
2008-11-27T15:08:07Z
[ "python", "multithreading", "kill", "terminate" ]
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
There is no official API to do that, no. You need to use platform API to kill the thread, e.g. pthread\_kill, or TerminateThread. You can access such API e.g. through pythonwin, or through ctypes. Notice that this is inherently unsafe. It will likely lead to uncollectable garbage (from local variables of the stack fr...
Is there any way to kill a Thread in Python?
323,972
399
2008-11-27T14:55:53Z
324,002
9
2008-11-27T15:12:07Z
[ "python", "multithreading", "kill", "terminate" ]
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
It is better if you don't kill a thread. A way could be to introduce a "try" block into the thread's cycle and to throw an exception when you want to stop the thread (for example a break/return/... that stops your for/while/...). I've used this on my app and it works...
Is there any way to kill a Thread in Python?
323,972
399
2008-11-27T14:55:53Z
325,027
8
2008-11-28T03:47:26Z
[ "python", "multithreading", "kill", "terminate" ]
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
You can kill a thread by installing trace into the thread that will exit the thread. See attached link for one possible implementation. [Kill a thread in Python](https://web.archive.org/web/20130503082442/http://mail.python.org/pipermail/python-list/2004-May/281943.html)
Is there any way to kill a Thread in Python?
323,972
399
2008-11-27T14:55:53Z
325,528
385
2008-11-28T11:19:54Z
[ "python", "multithreading", "kill", "terminate" ]
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
It is generally a bad pattern to kill a thread abruptly, in Python and in any language. Think of the following cases: * the thread is holding a critical resource that must be closed properly * the thread has created several other threads that must be killed as well. The nice way of handling this if you can afford it ...
Is there any way to kill a Thread in Python?
323,972
399
2008-11-27T14:55:53Z
1,667,825
44
2009-11-03T14:53:11Z
[ "python", "multithreading", "kill", "terminate" ]
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
If you are trying to terminate the whole program you can set the thread as a "daemon". see [Thread.daemon](http://docs.python.org/library/threading.html#threading.Thread.daemon)
Is there any way to kill a Thread in Python?
323,972
399
2008-11-27T14:55:53Z
7,752,174
42
2011-10-13T09:38:20Z
[ "python", "multithreading", "kill", "terminate" ]
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
A `multiprocessing.Process` can `p.terminate()` In the cases where I want to kill a thread, but do not want to use flags/locks/signals/semaphores/events/whatever, I promote the threads to full blown processes. For code that makes use of just a few threads the overhead is not that bad. E.g. this comes in handy to easi...
Is there any way to kill a Thread in Python?
323,972
399
2008-11-27T14:55:53Z
15,185,771
9
2013-03-03T12:42:30Z
[ "python", "multithreading", "kill", "terminate" ]
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
In Python, you simply cannot kill a Thread directly. If you do NOT really need to have a Thread (!), what you can do, instead of using the [*threading* package](http://docs.python.org/2/library/threading.html) , is to use the [*multiprocessing* package](http://docs.python.org/2/library/multiprocessing.html) . Here, to...
Is there any way to kill a Thread in Python?
323,972
399
2008-11-27T14:55:53Z
15,274,929
14
2013-03-07T15:23:22Z
[ "python", "multithreading", "kill", "terminate" ]
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
This is based on [thread2 -- killable threads (Python recipe)](http://code.activestate.com/recipes/496960-thread2-killable-threads/) You need to call PyThreadState\_SetasyncExc(), which is only available through ctypes. This has only been tested on Python 2.7.3, but it is likely to work with other recent 2.x releases...
Is there any way to kill a Thread in Python?
323,972
399
2008-11-27T14:55:53Z
16,146,048
7
2013-04-22T11:27:17Z
[ "python", "multithreading", "kill", "terminate" ]
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
``` from ctypes import * pthread = cdll.LoadLibrary("libpthread-2.15.so") pthread.pthread_cancel(c_ulong(t.ident)) ``` **t** is your `Thread` object. Read the python source (`Modules/threadmodule.c` and `Python/thread_pthread.h`) you can see the `Thread.ident` is an `pthread_t` type, so you can do a...
Is there any way to kill a Thread in Python?
323,972
399
2008-11-27T14:55:53Z
27,261,365
10
2014-12-03T00:07:06Z
[ "python", "multithreading", "kill", "terminate" ]
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
As others have mentioned, the norm is to set a stop flag. For something lightweight (no subclassing of Thread, no global variable), a lambda callback is an option. (Note the parentheses in `if stop()`.) ``` import threading import time def do_work(id, stop): print("I am thread", id) while True: print(...
split twice in the same expression?
324,132
5
2008-11-27T16:12:04Z
324,141
20
2008-11-27T16:16:23Z
[ "python" ]
Imagine I have the following: ``` inFile = "/adda/adas/sdas/hello.txt" # that instruction give me hello.txt Name = inFile.name.split("/") [-1] # that one give me the name I want - just hello Name1 = Name.split(".") [0] ``` Is there any chance to simplify that doing the same job in just one expression?
You can get what you want platform independently by using [os.path.basename](http://docs.python.org/library/os.path.html#os.path.basename) to get the last part of a path and then use [os.path.splitext](http://docs.python.org/library/os.path.html#os.path.splitext) to get the filename without extension. ``` from os.path...
What is the fastest way to parse large XML docs in Python?
324,214
38
2008-11-27T16:47:54Z
324,355
8
2008-11-27T17:53:36Z
[ "python", "xml", "performance", "parsing" ]
I am currently the following code based on Chapter 12.5 of the Python Cookbook: ``` from xml.parsers import expat class Element(object): def __init__(self, name, attributes): self.name = name self.attributes = attributes self.cdata = '' self.children = [] def addChild(self, ele...
I recommend you to use [lxml](http://lxml.de/), it's a python binding for the libxml2 library which is really fast. In my experience, libxml2 and expat have very similar performance. But I prefer libxml2 (and lxml for python) because it seems to be more actively developed and tested. Also libxml2 has more features. l...
What is the fastest way to parse large XML docs in Python?
324,214
38
2008-11-27T16:47:54Z
324,483
13
2008-11-27T19:00:41Z
[ "python", "xml", "performance", "parsing" ]
I am currently the following code based on Chapter 12.5 of the Python Cookbook: ``` from xml.parsers import expat class Element(object): def __init__(self, name, attributes): self.name = name self.attributes = attributes self.cdata = '' self.children = [] def addChild(self, ele...
Have you tried The cElementTree Module? cElementTree is included with Python 2.5 and later, as xml.etree.cElementTree. Refer the [benchmarks](http://effbot.org/zone/celementtree.htm). *removed dead ImageShack link*
What is the fastest way to parse large XML docs in Python?
324,214
38
2008-11-27T16:47:54Z
326,541
37
2008-11-28T20:03:02Z
[ "python", "xml", "performance", "parsing" ]
I am currently the following code based on Chapter 12.5 of the Python Cookbook: ``` from xml.parsers import expat class Element(object): def __init__(self, name, attributes): self.name = name self.attributes = attributes self.cdata = '' self.children = [] def addChild(self, ele...
I looks to me as if you do not need any DOM capabilities from your program. I would second the use of the (c)ElementTree library. If you use the iterparse function of the cElementTree module, you can work your way through the xml and deal with the events as they occur. Note however, Fredriks advice on using cElementTr...
What is the equivalent of map<int, vector<int> > in Python?
324,643
9
2008-11-27T21:00:47Z
324,648
10
2008-11-27T21:06:08Z
[ "python", "dictionary" ]
In C++ often do something like this: ``` typedef map<int, vector<int> > MyIndexType; ``` Where I then use it like this: ``` MyIndexType myIndex; for( ... some loop ...) { myIndex[someId].push_back(someVal); } ``` If there was no entry in the map the code will insert a new empty vector and then append to it. In P...
Something like this perhaps: ``` myIndex = {} for (someId,someVal) in collection: myIndex.setdefault(someId, []).append(someVal) ```
What is the equivalent of map<int, vector<int> > in Python?
324,643
9
2008-11-27T21:00:47Z
324,653
15
2008-11-27T21:10:23Z
[ "python", "dictionary" ]
In C++ often do something like this: ``` typedef map<int, vector<int> > MyIndexType; ``` Where I then use it like this: ``` MyIndexType myIndex; for( ... some loop ...) { myIndex[someId].push_back(someVal); } ``` If there was no entry in the map the code will insert a new empty vector and then append to it. In P...
You want to use: ``` from collections import defaultdict myIndex = defaultdict(list) myIndex[someId].append(someVal) ``` Standard Library [`defaultdict` objects](http://docs.python.org/library/collections.html#id3). Example usage from the Python documentation: ``` >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3),...
Strategies for speeding up batch ORM operations in Django
324,779
9
2008-11-27T23:01:18Z
325,066
15
2008-11-28T04:39:02Z
[ "python", "django", "batch-file", "orm" ]
One of my API calls can result in updates to a large number of objects (Django models). I'm running into performance issues with this since I'm updating each item individually, saving, and moving on to the next: ``` for item in Something.objects.filter(x='y'): item.a="something" item.save() ``` Sometimes my f...
The ticket you linked to is for bulk creation - if you're not relying on an overridden `save` method or pre/post save signals to do bits of work on save, [`QuerySet` has an `update` method](http://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once) which you can use to perform an `UPDATE...
Launch a shell command with in a python script, wait for the termination and return to the script
325,463
32
2008-11-28T10:42:03Z
325,467
7
2008-11-28T10:45:23Z
[ "python", "subprocess", "popen", "os.execl" ]
I've a python script that has to launch a shell command for every file in a dir: ``` import os files = os.listdir(".") for f in files: os.execlp("myscript", "myscript", f) ``` This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python ...
The `os.exec*()` functions *replace* the current programm with the new one. When this programm ends so does your process. You probably want `os.system()`.
Launch a shell command with in a python script, wait for the termination and return to the script
325,463
32
2008-11-28T10:42:03Z
325,474
55
2008-11-28T10:48:18Z
[ "python", "subprocess", "popen", "os.execl" ]
I've a python script that has to launch a shell command for every file in a dir: ``` import os files = os.listdir(".") for f in files: os.execlp("myscript", "myscript", f) ``` This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python ...
> subprocess: The `subprocess` module > allows you to spawn new processes, > connect to their input/output/error > pipes, and obtain their return codes. <http://docs.python.org/library/subprocess.html> Usage: ``` import subprocess process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) process.wait()...
Launch a shell command with in a python script, wait for the termination and return to the script
325,463
32
2008-11-28T10:42:03Z
325,495
39
2008-11-28T11:01:45Z
[ "python", "subprocess", "popen", "os.execl" ]
I've a python script that has to launch a shell command for every file in a dir: ``` import os files = os.listdir(".") for f in files: os.execlp("myscript", "myscript", f) ``` This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python ...
You can use [`subprocess.Popen`](http://docs.python.org/library/subprocess.html). There's a few ways to do it: ``` import subprocess cmd = ['/run/myscript', '--arg', 'value'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) for line in p.stdout: print line p.wait() print p.returncode ``` Or, if you don't care wh...
Launch a shell command with in a python script, wait for the termination and return to the script
325,463
32
2008-11-28T10:42:03Z
5,184,921
9
2011-03-03T18:29:29Z
[ "python", "subprocess", "popen", "os.execl" ]
I've a python script that has to launch a shell command for every file in a dir: ``` import os files = os.listdir(".") for f in files: os.execlp("myscript", "myscript", f) ``` This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python ...
The subprocess module has come along way since 2008. In particular [`check_call`](http://docs.python.org/library/subprocess.html#subprocess.check_call) and [`check_output`](http://docs.python.org/library/subprocess.html#subprocess.check_output) make simple subprocess stuff even easier. The `check_*` family of functions...
How can I dynamically get the set of classes from the current python module?
326,770
5
2008-11-28T22:07:18Z
326,789
9
2008-11-28T22:16:19Z
[ "python", "reflection", "metaprogramming" ]
I have a python module that defines a number of classes: ``` class A(object): def __call__(self): print "ran a" class B(object): def __call__(self): print "ran b" class C(object): def __call__(self): print "ran c" ``` From within the module, how might I add an attribute that give...
``` import sys getattr(sys.modules[__name__], 'A') ```