title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
How to access previous/next element while for looping?
323,750
<p>Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop?</p> <pre><code>l=[1,2,3] for item in l: if item==2: get_previous(l,item) </code></pre>
31
2008-11-27T13:22:19Z
323,910
<p>Expressed as a generator function:</p> <pre><code>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) </code></pre> <p>Usage:</p> <pre><code>for prev,item,next in neighborhood(l): print prev, item, next </code></pre> <p><strong>Edit:</strong> I thought it would reduce the readability, but this way seem to look better.</p>
52
2008-11-27T14:28:23Z
[ "python" ]
How to access previous/next element while for looping?
323,750
<p>Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop?</p> <pre><code>l=[1,2,3] for item in l: if item==2: get_previous(l,item) </code></pre>
31
2008-11-27T13:22:19Z
323,911
<p>When dealing with generators where you need some context, I often use the below utility function to give a sliding window view on an iterator:</p> <pre><code>import collections, itertools def window(it, winsize, step=1): """Sliding window iterator.""" it=iter(it) # Ensure we have an iterator l=collections.deque(itertools.islice(it, winsize)) while 1: # Continue till StopIteration gets raised. yield tuple(l) for i in range(step): l.append(it.next()) l.popleft() </code></pre> <p>It'll generate a view of the sequence N items at a time, shifting step places over. eg.</p> <pre><code>&gt;&gt;&gt; list(window([1,2,3,4,5],3)) [(1, 2, 3), (2, 3, 4), (3, 4, 5)] </code></pre> <p>When using in lookahead/behind situations where you also need to deal with numbers without having a next or previous value, you may want pad the sequence with an appropriate value such as None.</p> <pre><code>l= range(10) # Print adjacent numbers for cur, next in window(l + [None] ,2): if next is None: print "%d is the last number." % cur else: print "%d is followed by %d" % (cur,next) </code></pre>
6
2008-11-27T14:29:16Z
[ "python" ]
How to access previous/next element while for looping?
323,750
<p>Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop?</p> <pre><code>l=[1,2,3] for item in l: if item==2: get_previous(l,item) </code></pre>
31
2008-11-27T13:22:19Z
324,069
<p>Immediately previous? </p> <p>You mean the following, right?</p> <pre><code>previous = None for item in someList: if item == target: break previous = item # previous is the item before the target </code></pre> <p>If you want <em>n</em> previous items, you can do this with a kind of circular queue of size <em>n</em>.</p> <pre><code>queue = [] for item in someList: if item == target: break queue .append( item ) if len(queue ) &gt; n: queue .pop(0) if len(queue ) &lt; n: previous = None previous = previous[0] # previous is *n* before the target </code></pre>
0
2008-11-27T15:46:17Z
[ "python" ]
How to access previous/next element while for looping?
323,750
<p>Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop?</p> <pre><code>l=[1,2,3] for item in l: if item==2: get_previous(l,item) </code></pre>
31
2008-11-27T13:22:19Z
324,273
<pre><code>l=[1,2,3] for i,item in enumerate(l): if item==2: get_previous=l[i-1] print get_previous &gt;&gt;&gt;1 </code></pre>
7
2008-11-27T17:15:38Z
[ "python" ]
How to access previous/next element while for looping?
323,750
<p>Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop?</p> <pre><code>l=[1,2,3] for item in l: if item==2: get_previous(l,item) </code></pre>
31
2008-11-27T13:22:19Z
325,864
<p>Check out the looper utility from the <a href="http://pythonpaste.org/tempita/#bunch-and-looper">Tempita project</a>. It gives you a wrapper object around the loop item that provides properties such as previous, next, first, last etc.</p> <p>Take a look at the <a href="http://svn.pythonpaste.org/Tempita/trunk/tempita/_looper.py">source code</a> for the looper class, it is quite simple. There are other such loop helpers out there, but I cannot remember any others right now.</p> <p>Example:</p> <pre><code>> easy_install Tempita > python >>> from tempita import looper >>> for loop, i in looper([1, 2, 3]): ... print loop.previous, loop.item, loop.index, loop.next, loop.first, loop.last, loop.length, loop.odd, loop.even ... None 1 0 2 True False 3 True 0 1 2 1 3 False False 3 False 1 2 3 2 None False True 3 True 0 </code></pre>
5
2008-11-28T14:21:20Z
[ "python" ]
How to access previous/next element while for looping?
323,750
<p>Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop?</p> <pre><code>l=[1,2,3] for item in l: if item==2: get_previous(l,item) </code></pre>
31
2008-11-27T13:22:19Z
4,672,737
<p>Not very pythonic, but gets it done and is simple:</p> <pre><code>l=[1,2,3] for index in range(len(l)): if l[index]==2: l[index-1] </code></pre> <p>TO DO: protect the edges </p>
-1
2011-01-12T18:50:54Z
[ "python" ]
How to access previous/next element while for looping?
323,750
<p>Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop?</p> <pre><code>l=[1,2,3] for item in l: if item==2: get_previous(l,item) </code></pre>
31
2008-11-27T13:22:19Z
22,030,004
<p>I know this is old, but why not just use index?</p> <pre><code>some_list = ["bob", "bill", "barry"] for item in some_list: print "Item - " + item if some_list.index(item) != len(some_list) -1: next_item = some_list[some_list.index(item) + 1] print "Next item -", next_item else: print "Next item does not exist!" </code></pre> <p>this should return:</p> <p>Item - bob</p> <p>Next item - bill</p> <p>Item - bill</p> <p>Next item - barry</p> <p>Item - barry</p> <p>Next item does not exist!</p> <p>The same idea can be used to get the previous element as well.</p>
3
2014-02-26T01:40:44Z
[ "python" ]
How to access previous/next element while for looping?
323,750
<p>Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop?</p> <pre><code>l=[1,2,3] for item in l: if item==2: get_previous(l,item) </code></pre>
31
2008-11-27T13:22:19Z
23,531,068
<p>One simple way. </p> <pre><code>l=[1,2,3] for i,j in zip(l, l[1:]): print i, j </code></pre>
11
2014-05-08T01:10:28Z
[ "python" ]
Foreign key from one app into another in Django
323,763
<p>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?</p> <p>In other words, I have two apps, called cf and profiles, and in cf/models.py I have (amongst other things):</p> <pre><code>class Movie(models.Model): title = models.CharField(max_length=255) </code></pre> <p>and in profiles/models.py I want to have:</p> <pre><code>class MovieProperty(models.Model): movie = models.ForeignKey(Movie) </code></pre> <p>But I can't get it to work. I've tried:</p> <pre><code> movie = models.ForeignKey(cf.Movie) </code></pre> <p>and I've tried importing cf.Movie at the beginning of models.py, but I always get errors, such as:</p> <pre><code>NameError: name 'User' is not defined </code></pre> <p>Am I breaking the rules by trying to tie two apps together in this way, or have I just got the syntax wrong?</p>
49
2008-11-27T13:24:45Z
323,900
<p>OK - I've figured it out. You can do it, you just have to use the right import syntax. The correct syntax is:</p> <p>from prototype.cf.models import Movie</p> <p>My mistake was not specifying the ".models" part of that line. D'oh!</p>
6
2008-11-27T14:26:28Z
[ "python", "django", "django-models" ]
Foreign key from one app into another in Django
323,763
<p>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?</p> <p>In other words, I have two apps, called cf and profiles, and in cf/models.py I have (amongst other things):</p> <pre><code>class Movie(models.Model): title = models.CharField(max_length=255) </code></pre> <p>and in profiles/models.py I want to have:</p> <pre><code>class MovieProperty(models.Model): movie = models.ForeignKey(Movie) </code></pre> <p>But I can't get it to work. I've tried:</p> <pre><code> movie = models.ForeignKey(cf.Movie) </code></pre> <p>and I've tried importing cf.Movie at the beginning of models.py, but I always get errors, such as:</p> <pre><code>NameError: name 'User' is not defined </code></pre> <p>Am I breaking the rules by trying to tie two apps together in this way, or have I just got the syntax wrong?</p>
49
2008-11-27T13:24:45Z
323,905
<p>According to the docs, your second attempt should work:</p> <blockquote> <p>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:</p> </blockquote> <pre><code>class Car(models.Model): manufacturer = models.ForeignKey('production.Manufacturer') </code></pre> <p>Have you tried putting it into quotes?</p>
79
2008-11-27T14:27:45Z
[ "python", "django", "django-models" ]
Foreign key from one app into another in Django
323,763
<p>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?</p> <p>In other words, I have two apps, called cf and profiles, and in cf/models.py I have (amongst other things):</p> <pre><code>class Movie(models.Model): title = models.CharField(max_length=255) </code></pre> <p>and in profiles/models.py I want to have:</p> <pre><code>class MovieProperty(models.Model): movie = models.ForeignKey(Movie) </code></pre> <p>But I can't get it to work. I've tried:</p> <pre><code> movie = models.ForeignKey(cf.Movie) </code></pre> <p>and I've tried importing cf.Movie at the beginning of models.py, but I always get errors, such as:</p> <pre><code>NameError: name 'User' is not defined </code></pre> <p>Am I breaking the rules by trying to tie two apps together in this way, or have I just got the syntax wrong?</p>
49
2008-11-27T13:24:45Z
32,869,639
<p>It is also possible to pass the class itself:</p> <pre><code>from django.db import models from production import models as production_models class Car(models.Model): manufacturer = models.ForeignKey(production_models.Manufacturer) </code></pre>
12
2015-09-30T15:09:36Z
[ "python", "django", "django-models" ]
How to find out if there is data to be read from stdin on Windows in Python?
323,829
<p>This code</p> <pre><code>select.select([sys.stdin], [], [], 1.0) </code></pre> <p>does exactly what I want on Linux, but not in Windows.</p> <p>I've used <code>kbhit()</code> in <code>msvcrt</code> before to see if data is available on stdin for reading, but in this case it always returns <code>0</code>. Additionally <code>msvcrt.getch()</code> returns <code>'\xff'</code> whereas <code>sys.stdin.read(1)</code> returns <code>'\x01'</code>. It seems as if the msvcrt functions are not behaving properly.</p> <p>Unfortunately I can't use TCP sockets as I'm not in control of the application talking my Python program.</p>
5
2008-11-27T13:55:59Z
323,902
<p>In some rare situations, you might care what stdin is connected to. Mostly, you don't care -- you just read stdin.</p> <p>In <code>someprocess | python myprogram.py</code>, stdin is connected to a pipe; in this case, the stdout of the previous process. You simply read from <code>sys.stdin</code> and you're reading from the other process. [Note that in Windows, however, there's still (potentially) a "CON" device with a keyboard. It just won't be <code>sys.stdin</code>.]</p> <p>In <code>python myprogram.py &lt;someFile</code>, stdin is connected to a file. You simply read from <code>sys.stdin</code> and you're reading from the file.</p> <p>In <code>python myprogram.py</code>, stdin is left connected to the console (<code>/dev/ttyxx</code> in *nix). You simple read from <code>sys.stdin</code> and you're reading from the keyboard.</p> <p>Note the common theme in the above three cases. You simply read from <code>sys.stdin</code> and your program's environment defines everything for you. You don't check "to see if data is available on stdin for reading". It's already available.</p> <p>Sometimes, you want a keyboard interrupt (or other shenanigans). Python, BTW, has a keyboard interrupt as a first-class feature of the I/O elements. Control-C raises an interrupt during I/O (it won't break into a tight loop, but it will signal a program that prints periodically.)</p> <p>Sometimes you need to find out what kind of file <code>stdin</code> is connected to.</p> <p>Something like <code>os.isatty( sys.stdin.fileno() )</code> If <code>sys.stdin</code> is a TTY, you're program was left connected to the windows "CON" (the keyboard). If <code>sys.stdin</code> is not a TTY, it's connected to a file or a pipe.</p> <p><hr /></p> <p>Example</p> <pre><code>Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\slott&gt;python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; import sys &gt;&gt;&gt; os.isatty( sys.stdin.fileno() ) True &gt;&gt;&gt; </code></pre> <p>The value of <code>True</code> tells me Python is running without a file or pipe attached. <code>sys.stdin</code> is the keyboard. Using windows <code>kbhit</code> is needless.</p> <p>A value of <code>False</code> tells me Python is running with a file or pipe attached. <code>sys.stdin</code> is NOT the keyboard. Checking <code>kbhit</code> might be meaningful. Also, I could open the <code>CON:</code> device and read the keyboard directly, separate from <code>sys.stdin</code>.</p> <p><hr /></p> <p>I'm not sure why you need "to see if data is available on stdin for reading". It might help to update your question with additional details of what you're trying to accomplish.</p>
2
2008-11-27T14:26:53Z
[ "python" ]
How to find out if there is data to be read from stdin on Windows in Python?
323,829
<p>This code</p> <pre><code>select.select([sys.stdin], [], [], 1.0) </code></pre> <p>does exactly what I want on Linux, but not in Windows.</p> <p>I've used <code>kbhit()</code> in <code>msvcrt</code> before to see if data is available on stdin for reading, but in this case it always returns <code>0</code>. Additionally <code>msvcrt.getch()</code> returns <code>'\xff'</code> whereas <code>sys.stdin.read(1)</code> returns <code>'\x01'</code>. It seems as if the msvcrt functions are not behaving properly.</p> <p>Unfortunately I can't use TCP sockets as I'm not in control of the application talking my Python program.</p>
5
2008-11-27T13:55:59Z
3,541,638
<p>I run a thread that reads from stdin, then forward the data to a socket. The socket is selectable, so, stdin is selectable too.</p> <p>see: <a href="http://www.ideawu.com/blog/2010/08/how-to-select-stdin-in-python-windows.html" rel="nofollow">http://www.ideawu.com/blog/2010/08/how-to-select-stdin-in-python-windows.html</a></p>
1
2010-08-22T13:31:27Z
[ "python" ]
How to analyse .exe parameters inside the program?
323,866
<p>I have a program that can have a lot of parameters (we have over +30 differents options).</p> <p>Example: <code>myProgram.exe -t alpha 1 -prod 1 2 -sleep 200</code></p> <p>This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection of String parameters for each command.</p> <p>For the moment, we use string comparison and we can get the whole thing works (instance the concrete command and return the ICommand interface). The problem is we require to do a lot of IF everytime to get the good command.</p> <p>Do you have some pattern that can be used to extract all parameters from an EXE without using a lot of IF?</p> <p>The code is in C# but I think the logic can be any other language too...</p>
4
2008-11-27T14:13:40Z
323,886
<p>(Well, since this is tagged with Python):</p> <p>We use Python's <a href="http://docs.python.org/library/optparse.html" rel="nofollow">optparse</a> module for this purpose. It has a much friendlier API than lots of ifs.</p>
6
2008-11-27T14:18:48Z
[ "c#", "java", ".net", "python" ]
How to analyse .exe parameters inside the program?
323,866
<p>I have a program that can have a lot of parameters (we have over +30 differents options).</p> <p>Example: <code>myProgram.exe -t alpha 1 -prod 1 2 -sleep 200</code></p> <p>This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection of String parameters for each command.</p> <p>For the moment, we use string comparison and we can get the whole thing works (instance the concrete command and return the ICommand interface). The problem is we require to do a lot of IF everytime to get the good command.</p> <p>Do you have some pattern that can be used to extract all parameters from an EXE without using a lot of IF?</p> <p>The code is in C# but I think the logic can be any other language too...</p>
4
2008-11-27T14:13:40Z
323,887
<p>I'd be a little uncomfortable using a command line like that. First thing I'd say is "what does the first '1' mean, and why is it different to the second '1'?"</p> <p>Any time I write a command line utility that accepts an argument, I consider how easy it would be for a user to learn all the options. In this case, it looks like a bit of a hard task, IMHO.</p> <p>Maybe refactoring how the user passes the arguments would be a good idea. There's a reason why a lot of software takes key/value type parameters (e.g. myclient.exe -server=myServerName -config=debug) It takes a lot of load off the user, and also simplifies the argument parsing once it hits your code.</p>
1
2008-11-27T14:19:47Z
[ "c#", "java", ".net", "python" ]
How to analyse .exe parameters inside the program?
323,866
<p>I have a program that can have a lot of parameters (we have over +30 differents options).</p> <p>Example: <code>myProgram.exe -t alpha 1 -prod 1 2 -sleep 200</code></p> <p>This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection of String parameters for each command.</p> <p>For the moment, we use string comparison and we can get the whole thing works (instance the concrete command and return the ICommand interface). The problem is we require to do a lot of IF everytime to get the good command.</p> <p>Do you have some pattern that can be used to extract all parameters from an EXE without using a lot of IF?</p> <p>The code is in C# but I think the logic can be any other language too...</p>
4
2008-11-27T14:13:40Z
323,891
<p>Create a hash table which stores function pointers (in C# that'd be delegates) for handling each of the parameters, keyed using the parameter text. Then you just go through the command line in a loop and make calls to delegates based on what comes out of hash table lookups.</p>
5
2008-11-27T14:21:37Z
[ "c#", "java", ".net", "python" ]
How to analyse .exe parameters inside the program?
323,866
<p>I have a program that can have a lot of parameters (we have over +30 differents options).</p> <p>Example: <code>myProgram.exe -t alpha 1 -prod 1 2 -sleep 200</code></p> <p>This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection of String parameters for each command.</p> <p>For the moment, we use string comparison and we can get the whole thing works (instance the concrete command and return the ICommand interface). The problem is we require to do a lot of IF everytime to get the good command.</p> <p>Do you have some pattern that can be used to extract all parameters from an EXE without using a lot of IF?</p> <p>The code is in C# but I think the logic can be any other language too...</p>
4
2008-11-27T14:13:40Z
323,894
<p>The getopt function is very common for C programming. It can parse parameters for you. Here is a question (and answer) where to get it for C#: <a href="http://stackoverflow.com/questions/172443/getopt-library-for-c">http://stackoverflow.com/questions/172443/getopt-library-for-c</a> .</p> <p>Especially <a href="http://stackoverflow.com/questions/172443/getopt-library-for-c#172533">lappies</a> implementation looks like rather modern C# with attributes and such.</p>
4
2008-11-27T14:23:42Z
[ "c#", "java", ".net", "python" ]
How to analyse .exe parameters inside the program?
323,866
<p>I have a program that can have a lot of parameters (we have over +30 differents options).</p> <p>Example: <code>myProgram.exe -t alpha 1 -prod 1 2 -sleep 200</code></p> <p>This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection of String parameters for each command.</p> <p>For the moment, we use string comparison and we can get the whole thing works (instance the concrete command and return the ICommand interface). The problem is we require to do a lot of IF everytime to get the good command.</p> <p>Do you have some pattern that can be used to extract all parameters from an EXE without using a lot of IF?</p> <p>The code is in C# but I think the logic can be any other language too...</p>
4
2008-11-27T14:13:40Z
323,912
<p>A useful options library for C#: <a href="http://www.ndesk.org/Options" rel="nofollow">NDesk.Options</a></p>
5
2008-11-27T14:30:04Z
[ "c#", "java", ".net", "python" ]
How to analyse .exe parameters inside the program?
323,866
<p>I have a program that can have a lot of parameters (we have over +30 differents options).</p> <p>Example: <code>myProgram.exe -t alpha 1 -prod 1 2 -sleep 200</code></p> <p>This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection of String parameters for each command.</p> <p>For the moment, we use string comparison and we can get the whole thing works (instance the concrete command and return the ICommand interface). The problem is we require to do a lot of IF everytime to get the good command.</p> <p>Do you have some pattern that can be used to extract all parameters from an EXE without using a lot of IF?</p> <p>The code is in C# but I think the logic can be any other language too...</p>
4
2008-11-27T14:13:40Z
323,920
<p>I dont think this is too cludging.. </p> <pre><code>private void Main() { string c = "-t alpha 1 -prod 1 2 -sleep 200"; foreach (string incommand in Strings.Split(c, "-")) { HandleCommand(Strings.Split(incommand.Trim, " ")); } } public void HandleCommand(string[] c) { switch (c(0).ToLower) { case "t": Interaction.MsgBox("Command:" + c(0) + " params: " + c.Length - 1); break; case "prod": Interaction.MsgBox("Command:" + c(0) + " params: " + c.Length - 1); break; case "sleep": Interaction.MsgBox("Command:" + c(0) + " params: " + c.Length - 1); break; } } </code></pre> <p>Of course, instead of doing exactly same thing in those switch-statements, call appropriate functions or code.</p>
0
2008-11-27T14:34:54Z
[ "c#", "java", ".net", "python" ]
How to analyse .exe parameters inside the program?
323,866
<p>I have a program that can have a lot of parameters (we have over +30 differents options).</p> <p>Example: <code>myProgram.exe -t alpha 1 -prod 1 2 -sleep 200</code></p> <p>This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection of String parameters for each command.</p> <p>For the moment, we use string comparison and we can get the whole thing works (instance the concrete command and return the ICommand interface). The problem is we require to do a lot of IF everytime to get the good command.</p> <p>Do you have some pattern that can be used to extract all parameters from an EXE without using a lot of IF?</p> <p>The code is in C# but I think the logic can be any other language too...</p>
4
2008-11-27T14:13:40Z
324,013
<p>Just for fun, you can create a wrapper around the whole thing and work with strong names in your code. More work? Yes. But more fun and once you add a new command to the wrapper you can forget about it ;)</p> <pre><code>public class Form1 { private void main() { MyCommandHandler CommandLineHandler = new MyCommandHandler(); CommandLineHandler.SetInput = "-t alpha 1 -prod 1 2 -sleep 200"; //now we can use strong name to work with the variables: //CommandLineHandler.prod.ProdID //CommandLineHandler.prod.ProdInstanceID //CommandLineHandler.Alpha.AlhaValue() //CommandLineHandler.Sleep.Miliseconds() if (CommandLineHandler.Alpha.AlhaValue &gt; 255) { throw new Exception("Apha value out of bounds!"); } } } public class MyCommandHandler { private string[] values; public string SetInput { set { values = Strings.Split(value, "-"); } } //Handle Prod command public struct prodstructure { public string ProdID; public string ProdInstanceID; } public prodstructure prod { get { prodstructure ret = new prodstructure(); ret.ProdID = GetArgsForCommand("prod", 0); ret.ProdInstanceID = GetArgsForCommand("prod", 1); return ret; } } //Handle Apha command public struct Aphastructure { public int AlhaValue; } public Aphastructure Alpha { get { Aphastructure ret = new Aphastructure(); ret.AlhaValue = Convert.ToInt32(GetArgsForCommand("alpha", 0)); return ret; } } //Handle Sleep command public struct SleepStructure { public int Miliseconds; } public SleepStructure Sleep { get { SleepStructure ret = new SleepStructure(); ret.Miliseconds = Convert.ToInt32(GetArgsForCommand("sleep", 0)); return ret; } } private string GetArgsForCommand(string key, int item) { foreach (string c in values) { foreach (string cc in Strings.Split(c.Trim, " ")) { if (cc.ToLower == key.ToLower) { try { return Strings.Split(c.Trim, " ")(item + 1); } catch (Exception ex) { return ""; } } } } return ""; } } </code></pre>
1
2008-11-27T15:18:25Z
[ "c#", "java", ".net", "python" ]
How to analyse .exe parameters inside the program?
323,866
<p>I have a program that can have a lot of parameters (we have over +30 differents options).</p> <p>Example: <code>myProgram.exe -t alpha 1 -prod 1 2 -sleep 200</code></p> <p>This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection of String parameters for each command.</p> <p>For the moment, we use string comparison and we can get the whole thing works (instance the concrete command and return the ICommand interface). The problem is we require to do a lot of IF everytime to get the good command.</p> <p>Do you have some pattern that can be used to extract all parameters from an EXE without using a lot of IF?</p> <p>The code is in C# but I think the logic can be any other language too...</p>
4
2008-11-27T14:13:40Z
324,270
<p>The answer in Java, as is so often the case, is that someone has beaten you to it and released an excellent open source library to do this. Have a look at <a href="http://commons.apache.org/cli/" rel="nofollow"><strong>Apache CLI</strong></a>.</p>
1
2008-11-27T17:15:14Z
[ "c#", "java", ".net", "python" ]
How to analyse .exe parameters inside the program?
323,866
<p>I have a program that can have a lot of parameters (we have over +30 differents options).</p> <p>Example: <code>myProgram.exe -t alpha 1 -prod 1 2 -sleep 200</code></p> <p>This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection of String parameters for each command.</p> <p>For the moment, we use string comparison and we can get the whole thing works (instance the concrete command and return the ICommand interface). The problem is we require to do a lot of IF everytime to get the good command.</p> <p>Do you have some pattern that can be used to extract all parameters from an EXE without using a lot of IF?</p> <p>The code is in C# but I think the logic can be any other language too...</p>
4
2008-11-27T14:13:40Z
325,157
<p>Commonly, you can replace large if/else or switch/case constructs with a Dictionary. Where the if-criteria is the key and the code to execute is the value.</p> <p>For example, you could nave a <code>Dictionary&lt;string, ICommand&gt;</code> (or <code>Dictionary&lt;string, Type&gt;</code>), which you fill before you parse your command line.</p> <p>When you iterate over the passed in command line options, you simply look them up in the dictionary and "invoke" on the value which is the matching command (object) to execute (or alternatively use <code>Activate.CreateInstance(/*dictionary-value*/)</code> if you stored the type instead of a specific object instance).</p> <p>In C# 3.0 you could also something like <code>Dictionary&lt;string, System.Linq.Expressions.Expression&lt;T&gt;&gt;</code>, although this gets you pretty close to the actual if-statement - which is something you might want to have or not. YMMV.</p> <p>Some libraries provide you with the mere parsing of the command line arguments (like traditionally getopt() et al did) or can provide the whole package, including the invokation of actions upon the presence of specific command line arguments.</p>
0
2008-11-28T06:30:23Z
[ "c#", "java", ".net", "python" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
323,981
<p>You should never forcibly kill a thread without cooperating with it.</p> <p>Killing a thread removes any guarantees that try/finally blocks set up so you might leave locks locked, files open, etc.</p> <p>The only time you can argue that forcibly killing threads is a good idea is to kill a program fast, but never single threads.</p>
25
2008-11-27T14:58:49Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
323,993
<p>There is no official API to do that, no.</p> <p>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.</p> <p>Notice that this is inherently unsafe. It will likely lead to uncollectable garbage (from local variables of the stack frames that become garbage), and may lead to deadlocks, if the thread being killed has the GIL at the point when it is killed.</p>
89
2008-11-27T15:08:07Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
324,002
<p>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...</p>
9
2008-11-27T15:12:07Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
325,027
<p>You can kill a thread by installing trace into the thread that will exit the thread. See attached link for one possible implementation.</p> <p><a href="https://web.archive.org/web/20130503082442/http://mail.python.org/pipermail/python-list/2004-May/281943.html" rel="nofollow">Kill a thread in Python</a> </p>
8
2008-11-28T03:47:26Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
325,528
<p>It is generally a bad pattern to kill a thread abruptly, in Python and in any language. Think of the following cases:</p> <ul> <li>the thread is holding a critical resource that must be closed properly</li> <li>the thread has created several other threads that must be killed as well.</li> </ul> <p>The nice way of handling this if you can afford it (if you are managing your own threads) is to have an exit_request flag that each threads checks on regular interval to see if it is time for him to exit.</p> <p><strong>For example:</strong></p> <pre><code>import threading class StoppableThread(threading.Thread): """Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition.""" def __init__(self): super(StoppableThread, self).__init__() self._stop = threading.Event() def stop(self): self._stop.set() def stopped(self): return self._stop.isSet() </code></pre> <p>In this code, you should call stop() on the thread when you want it to exit, and wait for the thread to exit properly using join(). The thread should check the stop flag at regular intervals.</p> <p>There are cases however when you really need to kill a thread. An example is when you are wrapping an external library that is busy for long calls and you want to interrupt it.</p> <p>The following code allows (with some restrictions) to raise an Exception in a Python thread:</p> <pre><code>def _async_raise(tid, exctype): '''Raises an exception in the threads with id tid''' if not inspect.isclass(exctype): raise TypeError("Only types can be raised (not instances)") res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: # "if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect" ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0) raise SystemError("PyThreadState_SetAsyncExc failed") class ThreadWithExc(threading.Thread): '''A thread class that supports raising exception in the thread from another thread. ''' def _get_my_tid(self): """determines this (self's) thread id CAREFUL : this function is executed in the context of the caller thread, to get the identity of the thread represented by this instance. """ if not self.isAlive(): raise threading.ThreadError("the thread is not active") # do we have it cached? if hasattr(self, "_thread_id"): return self._thread_id # no, look for it in the _active dict for tid, tobj in threading._active.items(): if tobj is self: self._thread_id = tid return tid # TODO: in python 2.6, there's a simpler way to do : self.ident raise AssertionError("could not determine the thread's id") def raiseExc(self, exctype): """Raises the given exception type in the context of this thread. If the thread is busy in a system call (time.sleep(), socket.accept(), ...), the exception is simply ignored. If you are sure that your exception should terminate the thread, one way to ensure that it works is: t = ThreadWithExc( ... ) ... t.raiseExc( SomeException ) while t.isAlive(): time.sleep( 0.1 ) t.raiseExc( SomeException ) If the exception is to be caught by the thread, you need a way to check that your thread has caught it. CAREFUL : this function is executed in the context of the caller thread, to raise an excpetion in the context of the thread represented by this instance. """ _async_raise( self._get_my_tid(), exctype ) </code></pre> <p>As noted in the documentation, this is not a magic bullet because if the thread is busy outside the Python interpreter, it will not catch the interruption.</p> <p>A good usage pattern of this code is to have the thread catch a specific exception and perform the cleanup. That way, you can interrupt a task and still have proper cleanup.</p>
385
2008-11-28T11:19:54Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
1,667,825
<p>If you are trying to terminate the whole program you can set the thread as a "daemon". see <a href="http://docs.python.org/library/threading.html#threading.Thread.daemon">Thread.daemon</a></p>
44
2009-11-03T14:53:11Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
5,817,436
<blockquote> <p><strong>This is a bad answer, see the comments</strong></p> </blockquote> <p>Here's how to do it:</p> <pre><code>from threading import * ... for thread in enumerate(): if thread.isAlive(): try: thread._Thread__stop() except: print(str(thread.getName()) + ' could not be terminated')) </code></pre> <p>Give it a few seconds then your thread should be stopped. Check also the <code>thread._Thread__delete()</code> method.</p> <p>I'd recommend a <code>thread.quit()</code> method for convenience. For example if you have a socket in your thread, I'd recommend creating a <code>quit()</code> method in your socket-handle class, terminate the socket, then run a <code>thread._Thread__stop()</code> inside of your <code>quit()</code>.</p>
5
2011-04-28T10:52:30Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
7,752,174
<p>A <code>multiprocessing.Process</code> can <code>p.terminate()</code></p> <p>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.</p> <p>E.g. this comes in handy to easily terminate helper "threads" which execute blocking I/O</p> <p>The conversion is trivial: In related code replace all <code>threading.Thread</code> with <code>multiprocessing.Process</code> and all <code>queue.Queue</code> with <code>multiprocessing.Queue</code> and add the required calls of <code>p.terminate()</code> to your parent process which wants to kill its child <code>p</code></p> <p><a href="http://docs.python.org/release/3.1.3/library/multiprocessing.html">Python doc</a></p>
42
2011-10-13T09:38:20Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
15,185,771
<p>In Python, you simply cannot kill a Thread directly.</p> <p>If you do NOT really need to have a Thread (!), what you can do, instead of using the <a href="http://docs.python.org/2/library/threading.html" rel="nofollow"><em>threading</em> package </a>, is to use the <a href="http://docs.python.org/2/library/multiprocessing.html" rel="nofollow"><em>multiprocessing</em> package </a>. Here, to kill a process, you can simply call the method:</p> <pre><code>yourProcess.terminate() # kill the process! </code></pre> <p>Python will kill your process (on Unix through the SIGTERM signal, while on Windows through the TerminateProcess() call). Pay attention to use it while using a Queue or a Pipe! (it may corrupt the data in the Queue/Pipe)</p> <p>Note that the <em>multiprocessing.Event</em> and the <em>multiprocessing.Semaphore</em> work exactly in the same way of the <em>threading.Event</em> and the <em>threading.Semaphore</em> respectively. In fact, the first ones are clones of the latters.</p> <p>If you REALLY need to use a Thread, there is no way to kill it directly. What you can do, however, is to use a <em>"daemon thread"</em>. In fact, in Python, a Thread can be flagged as <em>daemon</em>:</p> <pre><code>yourThread.daemon = True # set the Thread as a "daemon thread" </code></pre> <p>The main program will exit when no alive non-daemon threads are left. In other words, when your main thread (which is, of course, a non-daemon thread) will finish its operations, the program will exit even if there are still some daemon threads working.</p> <p>Note that it is necessary to set a Thread as <em>daemon</em> before the <em>start()</em> method is called!</p> <p>Of course you can, and should, use <em>daemon</em> even with <em>multiprocessing</em>. Here, when the main process exits, it attempts to terminate all of its daemonic child processes.</p> <p>Finally, please, note that <em>sys.exit()</em> and <em>os.kill()</em> are not choices.</p>
9
2013-03-03T12:42:30Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
15,274,929
<p>This is based on <a href="http://code.activestate.com/recipes/496960-thread2-killable-threads/" rel="nofollow">thread2 -- killable threads (Python recipe)</a></p> <p>You need to call PyThreadState_SetasyncExc(), which is only available through ctypes.</p> <p>This has only been tested on Python 2.7.3, but it is likely to work with other recent 2.x releases.</p> <pre><code>import ctypes def terminate_thread(thread): """Terminates a python thread from another thread. :param thread: a threading.Thread instance """ if not thread.isAlive(): return exc = ctypes.py_object(SystemExit) res = ctypes.pythonapi.PyThreadState_SetAsyncExc( ctypes.c_long(thread.ident), exc) if res == 0: raise ValueError("nonexistent thread id") elif res &gt; 1: # """if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect""" ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None) raise SystemError("PyThreadState_SetAsyncExc failed") </code></pre>
14
2013-03-07T15:23:22Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
16,146,048
<pre><code> from ctypes import * pthread = cdll.LoadLibrary("libpthread-2.15.so") pthread.pthread_cancel(c_ulong(t.ident)) </code></pre> <p><strong>t</strong> is your <code>Thread</code> object.</p> <p>Read the python source (<code>Modules/threadmodule.c</code> and <code>Python/thread_pthread.h</code>) you can see the <code>Thread.ident</code> is an <code>pthread_t</code> type, so you can do anything <code>pthread</code> can do in python use <code>libpthread</code>.</p>
7
2013-04-22T11:27:17Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
23,920,936
<p>One thing I want to add is that if you read official documentation in <a href="https://docs.python.org/2/library/threading.html" rel="nofollow">threading lib Python</a>, it's recommended to avoid use of "demonic" threads, when you don't want threads end abruptly, with the flag that Paolo Rovelli <a href="http://stackoverflow.com/a/15185771">mentioned</a>.</p> <p>From official documentation:</p> <blockquote> <p>Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signaling mechanism such as an Event.</p> </blockquote> <p>I think that creating daemonic threads depends of your application, but in general (and in my opinion) it's better to avoid killing them or making them daemonic. In multiprocessing you can use <code>is_alive()</code> to check process status and "terminate" for finish them (Also you avoid GIL problems). But you can find more problems, sometimes, when you execute your code in Windows.</p> <p>And always remember that if you have "live threads", the Python interpreter will be running for wait them. (Because of this daemonic can help you if don't matter abruptly ends).</p>
4
2014-05-28T20:09:41Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
24,353,228
<p>If you really need the ability to kill a sub-task, use an alternate implementation. <code>multiprocessing</code> and <code>gevent</code> both support indiscriminately killing a "thread".</p> <p>Python's threading does not support cancellation. Do not even try. Your code is very likely to deadlock, corrupt or leak memory, or have other unintended "interesting" hard-to-debug effects which happen rarely and nondeterministically.</p>
0
2014-06-22T16:24:08Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
25,670,684
<p>It is definitely possible to implement a <code>Thread.stop</code> method as shown in the following example code:</p> <pre><code>import sys import threading import time class StopThread(StopIteration): pass threading.SystemExit = SystemExit, StopThread class Thread2(threading.Thread): def stop(self): self.__stop = True def _bootstrap(self): if threading._trace_hook is not None: raise ValueError('Cannot run thread with tracing!') self.__stop = False sys.settrace(self.__trace) super()._bootstrap() def __trace(self, frame, event, arg): if self.__stop: raise StopThread() return self.__trace class Thread3(threading.Thread): def _bootstrap(self, stop_thread=False): def stop(): nonlocal stop_thread stop_thread = True self.stop = stop def tracer(*_): if stop_thread: raise StopThread() return tracer sys.settrace(tracer) super()._bootstrap() ############################################################################### def main(): test1 = Thread2(target=printer) test1.start() time.sleep(1) test1.stop() test1.join() test2 = Thread2(target=speed_test) test2.start() time.sleep(1) test2.stop() test2.join() test3 = Thread3(target=speed_test) test3.start() time.sleep(1) test3.stop() test3.join() def printer(): while True: print(time.time() % 1) time.sleep(0.1) def speed_test(count=0): try: while True: count += 1 except StopThread: print('Count =', count) if __name__ == '__main__': main() </code></pre> <p>The <code>Thread3</code> class appears to run code approximately 33% faster than the <code>Thread2</code> class.</p>
6
2014-09-04T16:32:48Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
27,261,365
<p>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 <code>if stop()</code>.)</p> <pre><code>import threading import time def do_work(id, stop): print("I am thread", id) while True: print("I am thread {} doing something".format(id)) if stop(): print(" Exiting loop.") break print("Thread {}, signing off".format(id)) def main(): stop_threads = False workers = [] for id in range(0,3): tmp = threading.Thread(target=do_work, args=(id, lambda: stop_threads)) workers.append(tmp) tmp.start() time.sleep(3) print('main: done sleeping; time to stop the threads.') stop_threads = True for worker in workers: worker.join() print('Finis.') if __name__ == '__main__': main() </code></pre> <p>Replacing <code>print()</code> with a <code>pr()</code> function that always flushes (<code>sys.stdout.flush()</code>) may improve the precision of the shell output.</p> <p>(Only tested on Windows/Eclipse/Python3.3)</p>
10
2014-12-03T00:07:06Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
31,698,551
<p>This seems to work with pywin32 on windows 7</p> <pre><code>my_thread = threading.Thread() my_thread.start() my_thread._Thread__stop() </code></pre>
0
2015-07-29T10:59:06Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
33,520,140
<p>I think this is a pretty neat solution: <a href="http://code.activestate.com/recipes/496960-thread2-killable-threads/" rel="nofollow">http://code.activestate.com/recipes/496960-thread2-killable-threads/</a></p> <p>It allows a "thread to raise exceptions in the context of another thread". In this way, the terminated thread can handle the termination without regularly checking an abbort flag.</p>
-1
2015-11-04T11:01:57Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
36,631,765
<p>You can execute your command in a process and then kill it using the process id. I needed to sync between two thread one of which doesn’t return by itself.</p> <pre><code>processIds = [] def executeRecord(command): print(command) process = subprocess.Popen(command, stdout=subprocess.PIPE) processIds.append(process.pid) print(processIds[0]) #Command that doesn't return by itself process.stdout.read().decode("utf-8") return; def recordThread(command, timeOut): thread = Thread(target=executeRecord, args=(command,)) thread.start() thread.join(timeOut) os.kill(processIds.pop(), signal.SIGINT) return; </code></pre>
0
2016-04-14T19:01:09Z
[ "python", "multithreading", "kill", "terminate" ]
Is there any way to kill a Thread in Python?
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
399
2008-11-27T14:55:53Z
37,285,448
<p>Start the sub thread with setDaemon(True).</p> <pre><code>def bootstrap(_filename): mb = ModelBootstrap(filename=_filename) # Has many Daemon threads. All get stopped automatically when main thread is stopped. t = threading.Thread(target=bootstrap,args=('models.conf',)) t.setDaemon(False) while True: t.start() time.sleep(10) # I am just allowing the sub-thread to run for 10 sec. You can listen on an event to stop execution. print('Thread stopped') break </code></pre>
0
2016-05-17T20:13:43Z
[ "python", "multithreading", "kill", "terminate" ]
split twice in the same expression?
324,132
<p>Imagine I have the following:</p> <pre><code>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] </code></pre> <p>Is there any chance to simplify that doing the same job in just one expression?</p>
5
2008-11-27T16:12:04Z
324,139
<pre><code>&gt;&gt;&gt; inFile = "/adda/adas/sdas/hello.txt" &gt;&gt;&gt; inFile.split('/')[-1] 'hello.txt' &gt;&gt;&gt; inFile.split('/')[-1].split('.')[0] 'hello' </code></pre>
1
2008-11-27T16:16:15Z
[ "python" ]
split twice in the same expression?
324,132
<p>Imagine I have the following:</p> <pre><code>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] </code></pre> <p>Is there any chance to simplify that doing the same job in just one expression?</p>
5
2008-11-27T16:12:04Z
324,141
<p>You can get what you want platform independently by using <a href="http://docs.python.org/library/os.path.html#os.path.basename" rel="nofollow">os.path.basename</a> to get the last part of a path and then use <a href="http://docs.python.org/library/os.path.html#os.path.splitext" rel="nofollow">os.path.splitext</a> to get the filename without extension.</p> <pre><code>from os.path import basename, splitext pathname = "/adda/adas/sdas/hello.txt" name, extension = splitext(basename(pathname)) print name # --&gt; "hello" </code></pre> <p>Using <a href="http://docs.python.org/library/os.path.html#os.path.basename" rel="nofollow">os.path.basename</a> and <a href="http://docs.python.org/library/os.path.html#os.path.splitext" rel="nofollow">os.path.splitext</a> instead of str.split, or re.split is more proper (and therefore received more points then any other answer) because it does not break down on other <a href="http://en.wikipedia.org/wiki/Path_(computing)#Representations_of_paths_by_operating_system_and_shell" rel="nofollow">platforms that use different path separators (you would be surprised how varried this can be)</a>.</p> <p>It also carries most points because it answers your question for "one line" precisely and is aesthetically more pleasing then your example (even though that is debatable as are all questions of taste) </p>
20
2008-11-27T16:16:23Z
[ "python" ]
split twice in the same expression?
324,132
<p>Imagine I have the following:</p> <pre><code>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] </code></pre> <p>Is there any chance to simplify that doing the same job in just one expression?</p>
5
2008-11-27T16:12:04Z
324,172
<p>I'm pretty sure some Regex-Ninja*, would give you a more or less sane way to do that (or as I now see others have posted: ways to write two expressions on one line...)</p> <p>But I'm wondering why you want to do split it with just one expression? For such a simple split, it's probably faster to do two than to create some advanced either-or logic. If you split twice it's safer too: </p> <p>I guess you want to separate the path, the file name and the file extension, if you split on '/' first you know the filename should be in the last array index, then you can try to split just the last index to see if you can find the file extension or not. Then you don't need to care if ther is dots in the path names.</p> <p>*(Any <em>sane</em> users of regular expressions, should not be offended. ;)</p>
0
2008-11-27T16:28:50Z
[ "python" ]
split twice in the same expression?
324,132
<p>Imagine I have the following:</p> <pre><code>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] </code></pre> <p>Is there any chance to simplify that doing the same job in just one expression?</p>
5
2008-11-27T16:12:04Z
324,175
<p>if it is always going to be a path like the above you can use os.path.split and os.path.splitext </p> <p>The following example will print just the hello</p> <pre><code>from os.path import split, splitext path = "/adda/adas/sdas/hello.txt" print splitext(split(path)[1])[0] </code></pre> <p>For more info see <a href="https://docs.python.org/library/os.path.html" rel="nofollow">https://docs.python.org/library/os.path.html</a></p>
1
2008-11-27T16:30:01Z
[ "python" ]
split twice in the same expression?
324,132
<p>Imagine I have the following:</p> <pre><code>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] </code></pre> <p>Is there any chance to simplify that doing the same job in just one expression?</p>
5
2008-11-27T16:12:04Z
324,684
<p>Answering the question in the topic rather than trying to analyze the example...</p> <p>You really want to use <a href="http://stackoverflow.com/questions/324132/split-twice-in-the-same-expression#324141">Florians</a> solution if you want to split paths, but if you promise not to use this for path parsing...</p> <p>You can use <a href="https://docs.python.org/library/re.html#module-contents" rel="nofollow">re.split()</a> to split using several separators by or:ing them with a '|', have a look at this:</p> <pre><code>import re inFile = "/adda/adas/sdas/hello.txt" print re.split('\.|/', inFile)[-2] </code></pre>
2
2008-11-27T21:35:48Z
[ "python" ]
What is the fastest way to parse large XML docs in Python?
324,214
<p>I am currently the following code based on Chapter 12.5 of the Python Cookbook:</p> <pre><code>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, element): self.children.append(element) def getAttribute(self,key): return self.attributes.get(key) def getData(self): return self.cdata def getElements(self, name=''): if name: return [c for c in self.children if c.name == name] else: return list(self.children) class Xml2Obj(object): def __init__(self): self.root = None self.nodeStack = [] def StartElement(self, name, attributes): element = Element(name.encode(), attributes) if self.nodeStack: parent = self.nodeStack[-1] parent.addChild(element) else: self.root = element self.nodeStack.append(element) def EndElement(self, name): self.nodeStack.pop() def CharacterData(self,data): if data.strip(): data = data.encode() element = self.nodeStack[-1] element.cdata += data def Parse(self, filename): Parser = expat.ParserCreate() Parser.StartElementHandler = self.StartElement Parser.EndElementHandler = self.EndElement Parser.CharacterDataHandler = self.CharacterData ParserStatus = Parser.Parse(open(filename).read(),1) return self.root </code></pre> <p>I am working with XML docs about 1 GB in size. Does anyone know a faster way to parse these?</p>
38
2008-11-27T16:47:54Z
324,236
<p>Registering callbacks slows down the parsing tremendously. [EDIT]This is because the (fast) C code has to invoke the python interpreter which is just not as fast as C. Basically, you're using the C code to read the file (fast) and then build the DOM in Python (slow).[/EDIT]</p> <p>Try to use xml.etree.ElementTree which is implemented 100% in C and which can parse XML without any callbacks to python code.</p> <p>After the document has been parsed, you can filter it to get what you want.</p> <p>If that's still too slow and you don't need a DOM another option is to read the file into a string and use simple string operations to process it.</p>
3
2008-11-27T16:56:38Z
[ "python", "xml", "performance", "parsing" ]
What is the fastest way to parse large XML docs in Python?
324,214
<p>I am currently the following code based on Chapter 12.5 of the Python Cookbook:</p> <pre><code>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, element): self.children.append(element) def getAttribute(self,key): return self.attributes.get(key) def getData(self): return self.cdata def getElements(self, name=''): if name: return [c for c in self.children if c.name == name] else: return list(self.children) class Xml2Obj(object): def __init__(self): self.root = None self.nodeStack = [] def StartElement(self, name, attributes): element = Element(name.encode(), attributes) if self.nodeStack: parent = self.nodeStack[-1] parent.addChild(element) else: self.root = element self.nodeStack.append(element) def EndElement(self, name): self.nodeStack.pop() def CharacterData(self,data): if data.strip(): data = data.encode() element = self.nodeStack[-1] element.cdata += data def Parse(self, filename): Parser = expat.ParserCreate() Parser.StartElementHandler = self.StartElement Parser.EndElementHandler = self.EndElement Parser.CharacterDataHandler = self.CharacterData ParserStatus = Parser.Parse(open(filename).read(),1) return self.root </code></pre> <p>I am working with XML docs about 1 GB in size. Does anyone know a faster way to parse these?</p>
38
2008-11-27T16:47:54Z
324,355
<p>I recommend you to use <a href="http://lxml.de/" rel="nofollow">lxml</a>, it's a python binding for the libxml2 library which is really fast. </p> <p>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.</p> <p>lxml is mostly API compatible with <a href="http://docs.python.org/lib/module-xml.etree.ElementTree.html" rel="nofollow">xml.etree.ElementTree</a>. And there is good documentation in its web site.</p>
8
2008-11-27T17:53:36Z
[ "python", "xml", "performance", "parsing" ]
What is the fastest way to parse large XML docs in Python?
324,214
<p>I am currently the following code based on Chapter 12.5 of the Python Cookbook:</p> <pre><code>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, element): self.children.append(element) def getAttribute(self,key): return self.attributes.get(key) def getData(self): return self.cdata def getElements(self, name=''): if name: return [c for c in self.children if c.name == name] else: return list(self.children) class Xml2Obj(object): def __init__(self): self.root = None self.nodeStack = [] def StartElement(self, name, attributes): element = Element(name.encode(), attributes) if self.nodeStack: parent = self.nodeStack[-1] parent.addChild(element) else: self.root = element self.nodeStack.append(element) def EndElement(self, name): self.nodeStack.pop() def CharacterData(self,data): if data.strip(): data = data.encode() element = self.nodeStack[-1] element.cdata += data def Parse(self, filename): Parser = expat.ParserCreate() Parser.StartElementHandler = self.StartElement Parser.EndElementHandler = self.EndElement Parser.CharacterDataHandler = self.CharacterData ParserStatus = Parser.Parse(open(filename).read(),1) return self.root </code></pre> <p>I am working with XML docs about 1 GB in size. Does anyone know a faster way to parse these?</p>
38
2008-11-27T16:47:54Z
324,483
<p>Have you tried The cElementTree Module?</p> <p>cElementTree is included with Python 2.5 and later, as xml.etree.cElementTree. Refer the <a href="http://effbot.org/zone/celementtree.htm" rel="nofollow">benchmarks</a>.</p> <p><em>removed dead ImageShack link</em></p>
13
2008-11-27T19:00:41Z
[ "python", "xml", "performance", "parsing" ]
What is the fastest way to parse large XML docs in Python?
324,214
<p>I am currently the following code based on Chapter 12.5 of the Python Cookbook:</p> <pre><code>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, element): self.children.append(element) def getAttribute(self,key): return self.attributes.get(key) def getData(self): return self.cdata def getElements(self, name=''): if name: return [c for c in self.children if c.name == name] else: return list(self.children) class Xml2Obj(object): def __init__(self): self.root = None self.nodeStack = [] def StartElement(self, name, attributes): element = Element(name.encode(), attributes) if self.nodeStack: parent = self.nodeStack[-1] parent.addChild(element) else: self.root = element self.nodeStack.append(element) def EndElement(self, name): self.nodeStack.pop() def CharacterData(self,data): if data.strip(): data = data.encode() element = self.nodeStack[-1] element.cdata += data def Parse(self, filename): Parser = expat.ParserCreate() Parser.StartElementHandler = self.StartElement Parser.EndElementHandler = self.EndElement Parser.CharacterDataHandler = self.CharacterData ParserStatus = Parser.Parse(open(filename).read(),1) return self.root </code></pre> <p>I am working with XML docs about 1 GB in size. Does anyone know a faster way to parse these?</p>
38
2008-11-27T16:47:54Z
324,680
<p>If your application is performance-sensitive and likely to encounter large files (like you said, > 1GB) then I'd <strong>strongly</strong> advise against using the code you're showing in your question for the simple reason that <em>it loads the entire document into RAM</em>. I would encourage you to rethink your design (if at all possible) to avoid holding the whole document tree in RAM at once. Not knowing what your application's requirements are, I can't properly suggest any specific approach, other than the generic piece of advice to try to use an "event-based" design.</p>
4
2008-11-27T21:30:57Z
[ "python", "xml", "performance", "parsing" ]
What is the fastest way to parse large XML docs in Python?
324,214
<p>I am currently the following code based on Chapter 12.5 of the Python Cookbook:</p> <pre><code>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, element): self.children.append(element) def getAttribute(self,key): return self.attributes.get(key) def getData(self): return self.cdata def getElements(self, name=''): if name: return [c for c in self.children if c.name == name] else: return list(self.children) class Xml2Obj(object): def __init__(self): self.root = None self.nodeStack = [] def StartElement(self, name, attributes): element = Element(name.encode(), attributes) if self.nodeStack: parent = self.nodeStack[-1] parent.addChild(element) else: self.root = element self.nodeStack.append(element) def EndElement(self, name): self.nodeStack.pop() def CharacterData(self,data): if data.strip(): data = data.encode() element = self.nodeStack[-1] element.cdata += data def Parse(self, filename): Parser = expat.ParserCreate() Parser.StartElementHandler = self.StartElement Parser.EndElementHandler = self.EndElement Parser.CharacterDataHandler = self.CharacterData ParserStatus = Parser.Parse(open(filename).read(),1) return self.root </code></pre> <p>I am working with XML docs about 1 GB in size. Does anyone know a faster way to parse these?</p>
38
2008-11-27T16:47:54Z
326,541
<p>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. </p> <p>Note however, Fredriks advice on using cElementTree <a href="http://effbot.org/zone/element-iterparse.htm" rel="nofollow">iterparse function</a>:</p> <blockquote> <p>to parse large files, you can get rid of elements as soon as you’ve processed them:</p> </blockquote> <pre><code>for event, elem in iterparse(source): if elem.tag == "record": ... process record elements ... elem.clear() </code></pre> <blockquote> <p>The above pattern has one drawback; it does not clear the root element, so you will end up with a single element with lots of empty child elements. If your files are huge, rather than just large, this might be a problem. To work around this, you need to get your hands on the root element. The easiest way to do this is to enable start events, and save a reference to the first element in a variable:</p> </blockquote> <pre><code># get an iterable context = iterparse(source, events=("start", "end")) # turn it into an iterator context = iter(context) # get the root element event, root = context.next() for event, elem in context: if event == "end" and elem.tag == "record": ... process record elements ... root.clear() </code></pre> <p>The <a href="http://codespeak.net/lxml/FAQ.html#why-can-t-i-just-delete-parents-or-clear-the-root-node-in-iterparse" rel="nofollow">lxml.iterparse()</a> does not allow this.</p>
37
2008-11-28T20:03:02Z
[ "python", "xml", "performance", "parsing" ]
What is the fastest way to parse large XML docs in Python?
324,214
<p>I am currently the following code based on Chapter 12.5 of the Python Cookbook:</p> <pre><code>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, element): self.children.append(element) def getAttribute(self,key): return self.attributes.get(key) def getData(self): return self.cdata def getElements(self, name=''): if name: return [c for c in self.children if c.name == name] else: return list(self.children) class Xml2Obj(object): def __init__(self): self.root = None self.nodeStack = [] def StartElement(self, name, attributes): element = Element(name.encode(), attributes) if self.nodeStack: parent = self.nodeStack[-1] parent.addChild(element) else: self.root = element self.nodeStack.append(element) def EndElement(self, name): self.nodeStack.pop() def CharacterData(self,data): if data.strip(): data = data.encode() element = self.nodeStack[-1] element.cdata += data def Parse(self, filename): Parser = expat.ParserCreate() Parser.StartElementHandler = self.StartElement Parser.EndElementHandler = self.EndElement Parser.CharacterDataHandler = self.CharacterData ParserStatus = Parser.Parse(open(filename).read(),1) return self.root </code></pre> <p>I am working with XML docs about 1 GB in size. Does anyone know a faster way to parse these?</p>
38
2008-11-27T16:47:54Z
326,949
<p>Apparently <a href="http://www.reportlab.org/pyrxp.html" rel="nofollow">PyRXP</a> is really fast.</p> <p>They claim it is the fastest parser - but cElementTree isn't in their stats list.</p>
1
2008-11-29T00:17:43Z
[ "python", "xml", "performance", "parsing" ]
What is the fastest way to parse large XML docs in Python?
324,214
<p>I am currently the following code based on Chapter 12.5 of the Python Cookbook:</p> <pre><code>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, element): self.children.append(element) def getAttribute(self,key): return self.attributes.get(key) def getData(self): return self.cdata def getElements(self, name=''): if name: return [c for c in self.children if c.name == name] else: return list(self.children) class Xml2Obj(object): def __init__(self): self.root = None self.nodeStack = [] def StartElement(self, name, attributes): element = Element(name.encode(), attributes) if self.nodeStack: parent = self.nodeStack[-1] parent.addChild(element) else: self.root = element self.nodeStack.append(element) def EndElement(self, name): self.nodeStack.pop() def CharacterData(self,data): if data.strip(): data = data.encode() element = self.nodeStack[-1] element.cdata += data def Parse(self, filename): Parser = expat.ParserCreate() Parser.StartElementHandler = self.StartElement Parser.EndElementHandler = self.EndElement Parser.CharacterDataHandler = self.CharacterData ParserStatus = Parser.Parse(open(filename).read(),1) return self.root </code></pre> <p>I am working with XML docs about 1 GB in size. Does anyone know a faster way to parse these?</p>
38
2008-11-27T16:47:54Z
33,815,832
<p><strong>expat ParseFile</strong> works well if you don't need to store the entire tree in memory, which will sooner or later blow your RAM for large files:</p> <pre><code>import xml.parsers.expat parser = xml.parsers.expat.ParserCreate() parser.ParseFile(open('path.xml', 'r')) </code></pre> <p>It reads the files into chunks, and feeds them to the parser without exploding RAM.</p> <p>Doc: <a href="https://docs.python.org/2/library/pyexpat.html#xml.parsers.expat.xmlparser.ParseFile" rel="nofollow">https://docs.python.org/2/library/pyexpat.html#xml.parsers.expat.xmlparser.ParseFile</a></p>
1
2015-11-19T22:50:42Z
[ "python", "xml", "performance", "parsing" ]
Problem with Boolean Expression with a string value from a lIst
324,506
<p>I have the following problem:</p> <pre><code> # line is a line from a file that contains ["baa","beee","0"] line = TcsLine.split(",") NumPFCs = eval(line[2]) if NumPFCs==0: print line </code></pre> <p>I want to print all the lines from the file if the second position of the list has a value == 0.</p> <p>I print the lines but after that the following happens: Traceback (most recent call last):</p> <p>['baaa', 'beee', '0', '\n']</p> <p><strong><em>BUT after I have the next ERROR</em></strong></p> <pre><code>ilation.py", line 141, in ? getZeroPFcs() ilation.py", line 110, in getZeroPFcs NumPFCs = eval(line[2]) File "&lt;string&gt;", line 0 </code></pre> <p>Can you please help me? thanks</p> <p>What0s</p>
1
2008-11-27T19:16:46Z
324,524
<p>Your question is kind of hard to read, but using eval there is definitely not a good idea. Either just do a direct string comparison:</p> <pre><code>line=TcsLine.split(",") if line[2] == "0": print line </code></pre> <p>or use int</p> <pre><code>line=TcsLine.split(",") if int(line[2]) == 0: print line </code></pre> <p>Either way, your bad data will fail you.</p> <p>I'd also recomment reading <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a>.</p>
0
2008-11-27T19:30:26Z
[ "python" ]
Problem with Boolean Expression with a string value from a lIst
324,506
<p>I have the following problem:</p> <pre><code> # line is a line from a file that contains ["baa","beee","0"] line = TcsLine.split(",") NumPFCs = eval(line[2]) if NumPFCs==0: print line </code></pre> <p>I want to print all the lines from the file if the second position of the list has a value == 0.</p> <p>I print the lines but after that the following happens: Traceback (most recent call last):</p> <p>['baaa', 'beee', '0', '\n']</p> <p><strong><em>BUT after I have the next ERROR</em></strong></p> <pre><code>ilation.py", line 141, in ? getZeroPFcs() ilation.py", line 110, in getZeroPFcs NumPFCs = eval(line[2]) File "&lt;string&gt;", line 0 </code></pre> <p>Can you please help me? thanks</p> <p>What0s</p>
1
2008-11-27T19:16:46Z
324,525
<p>There are a few issues I see in your code segment:</p> <ol> <li>you make an assumption that list always has at least 3 elements</li> <li>eval will raise exception if containing string isn't valid python</li> <li>you say you want second element, but you access the 3rd element.</li> </ol> <p>This is a safer way to do this</p> <pre><code>line=TcsLine.split(",") if len(line) &gt;=3 and line[2].rfind("0") != -1: print line </code></pre>
0
2008-11-27T19:31:04Z
[ "python" ]
Problem with Boolean Expression with a string value from a lIst
324,506
<p>I have the following problem:</p> <pre><code> # line is a line from a file that contains ["baa","beee","0"] line = TcsLine.split(",") NumPFCs = eval(line[2]) if NumPFCs==0: print line </code></pre> <p>I want to print all the lines from the file if the second position of the list has a value == 0.</p> <p>I print the lines but after that the following happens: Traceback (most recent call last):</p> <p>['baaa', 'beee', '0', '\n']</p> <p><strong><em>BUT after I have the next ERROR</em></strong></p> <pre><code>ilation.py", line 141, in ? getZeroPFcs() ilation.py", line 110, in getZeroPFcs NumPFCs = eval(line[2]) File "&lt;string&gt;", line 0 </code></pre> <p>Can you please help me? thanks</p> <p>What0s</p>
1
2008-11-27T19:16:46Z
324,662
<p>I'd recommend using a regular expression to capture all of the variants of how 0 can be specified: with double-quotes, without any quotes, with single quotes, with extra whitespace outside the quotes, with whitespace inside the quotes, how you want the square brackets handled, etc.</p>
0
2008-11-27T21:15:36Z
[ "python" ]
Problem with Boolean Expression with a string value from a lIst
324,506
<p>I have the following problem:</p> <pre><code> # line is a line from a file that contains ["baa","beee","0"] line = TcsLine.split(",") NumPFCs = eval(line[2]) if NumPFCs==0: print line </code></pre> <p>I want to print all the lines from the file if the second position of the list has a value == 0.</p> <p>I print the lines but after that the following happens: Traceback (most recent call last):</p> <p>['baaa', 'beee', '0', '\n']</p> <p><strong><em>BUT after I have the next ERROR</em></strong></p> <pre><code>ilation.py", line 141, in ? getZeroPFcs() ilation.py", line 110, in getZeroPFcs NumPFCs = eval(line[2]) File "&lt;string&gt;", line 0 </code></pre> <p>Can you please help me? thanks</p> <p>What0s</p>
1
2008-11-27T19:16:46Z
324,686
<p>Let me explain a little what you do here.</p> <p>If you write:</p> <pre><code>NumPFCs = eval(line[2]) </code></pre> <p>the order of evaluation is:</p> <ul> <li>take the second character of the string line, i.e. a quote '"'</li> <li>eval this quote as a python expression, which is an error.</li> </ul> <p>If you write it instead as:</p> <pre><code>NumPFCs = eval(line)[2] </code></pre> <p>then the order of evaluation is:</p> <ul> <li>eval the line, producing a python list</li> <li>take the second element of that list, which is a one-character string: "0"</li> <li>a string cannot be compared with a number; this is an error too.</li> </ul> <p>In your terms, you want to do the following:</p> <pre><code>NumPFCs = eval(eval(line)[2]) </code></pre> <p>or, slightly better, compare NumPFCs to a string:</p> <pre><code>if NumPFCs == "0": </code></pre> <p>but the ways this could go wrong are almost innumerable. You should forget about <code>eval</code> and try to use other methods: string splitting, regular expressions etc. Others have already provided some suggestions, and I'm sure more will follow.</p>
1
2008-11-27T21:38:47Z
[ "python" ]
Problem with Boolean Expression with a string value from a lIst
324,506
<p>I have the following problem:</p> <pre><code> # line is a line from a file that contains ["baa","beee","0"] line = TcsLine.split(",") NumPFCs = eval(line[2]) if NumPFCs==0: print line </code></pre> <p>I want to print all the lines from the file if the second position of the list has a value == 0.</p> <p>I print the lines but after that the following happens: Traceback (most recent call last):</p> <p>['baaa', 'beee', '0', '\n']</p> <p><strong><em>BUT after I have the next ERROR</em></strong></p> <pre><code>ilation.py", line 141, in ? getZeroPFcs() ilation.py", line 110, in getZeroPFcs NumPFCs = eval(line[2]) File "&lt;string&gt;", line 0 </code></pre> <p>Can you please help me? thanks</p> <p>What0s</p>
1
2008-11-27T19:16:46Z
325,193
<p>There are many ways of skinning a cat, as it were :)</p> <p>Before we begin though, <strong>don't use eval on strings that are not yours</strong> so if the string has ever left your program; i.e. it has stayed in a file, sent over a network, someone can send in something nasty. And if someone can, you can be sure someone will.</p> <p>And you might want to look over your data format. Putting strings like ["baa","beee","0", "\n"] in a file does not make much sense to me.</p> <p>The first and simplest way would be to just strip away the stuff you don't need and to a string comparison. This would work as long as the '0'-string always looks the same and you're not really after the integer value 0, only the character pattern:</p> <pre><code>TcsLine = '["baa","beee","0"]' line = TcsLine.strip('[]').split(",") if line[2] == '"0"': print line </code></pre> <p><hr /></p> <p>The second way would be to similar to the first except that we cast the numeric string to an integer, yielding the integer value you were looking for (but printing 'line' without all the quotation marks):</p> <pre><code>TcsLine = '["baa","beee","0"]' line = [e.strip('"') for e in TcsLine.strip('[]').split(",")] NumPFCs = int(line[2]) if NumPFCs==0: print line </code></pre> <p><hr /></p> <p>Could it be that the string is actually a json array? Then I would probably go get <a href="http://pypi.python.org/pypi/simplejson" rel="nofollow">simplejson</a> to parse it properly if I were running Python&lt;2.6 or just import json on Python>=2.6. Then cast the resulting '0'-string to an integer as in the previous example.</p> <pre><code>TcsLine = '["baa","beee","0"]' #import json # for &gt;= Python2.6 import simplejson as json # for &lt;Python2.6 line = json.loads(TcsLine) NumPFCs = int(line[2]) if NumPFCs==0: print line </code></pre>
0
2008-11-28T07:00:40Z
[ "python" ]
What is the equivalent of map<int, vector<int> > in Python?
324,643
<p>In C++ often do something like this:</p> <pre><code>typedef map&lt;int, vector&lt;int&gt; &gt; MyIndexType; </code></pre> <p>Where I then use it like this:</p> <pre><code>MyIndexType myIndex; for( ... some loop ...) { myIndex[someId].push_back(someVal); } </code></pre> <p>If there was no entry in the map the code will insert a new empty vector and then append to it.</p> <p>In Python it would look like this:</p> <pre><code>myIndex = {} for (someId,someVal) in collection: try: myIndex[someId].append(someVal) except KeyError: myIndex[someId] = [someVal] </code></pre> <p>The try except is a bit ugly here. Is there a way to tell the dictionary an object type to insert when a KeyError is encountered at dictionary declaration time?</p>
9
2008-11-27T21:00:47Z
324,648
<p>Something like this perhaps:</p> <pre><code>myIndex = {} for (someId,someVal) in collection: myIndex.setdefault(someId, []).append(someVal) </code></pre>
10
2008-11-27T21:06:08Z
[ "python", "dictionary" ]
What is the equivalent of map<int, vector<int> > in Python?
324,643
<p>In C++ often do something like this:</p> <pre><code>typedef map&lt;int, vector&lt;int&gt; &gt; MyIndexType; </code></pre> <p>Where I then use it like this:</p> <pre><code>MyIndexType myIndex; for( ... some loop ...) { myIndex[someId].push_back(someVal); } </code></pre> <p>If there was no entry in the map the code will insert a new empty vector and then append to it.</p> <p>In Python it would look like this:</p> <pre><code>myIndex = {} for (someId,someVal) in collection: try: myIndex[someId].append(someVal) except KeyError: myIndex[someId] = [someVal] </code></pre> <p>The try except is a bit ugly here. Is there a way to tell the dictionary an object type to insert when a KeyError is encountered at dictionary declaration time?</p>
9
2008-11-27T21:00:47Z
324,653
<p>You want to use:</p> <pre><code>from collections import defaultdict myIndex = defaultdict(list) myIndex[someId].append(someVal) </code></pre> <p>Standard Library <a href="http://docs.python.org/library/collections.html#id3" rel="nofollow"><code>defaultdict</code> objects</a>.</p> <p>Example usage from the Python documentation:</p> <pre><code>&gt;&gt;&gt; s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] &gt;&gt;&gt; d = defaultdict(list) &gt;&gt;&gt; for k, v in s: d[k].append(v) &gt;&gt;&gt; d.items() [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] </code></pre>
15
2008-11-27T21:10:23Z
[ "python", "dictionary" ]
What is the equivalent of map<int, vector<int> > in Python?
324,643
<p>In C++ often do something like this:</p> <pre><code>typedef map&lt;int, vector&lt;int&gt; &gt; MyIndexType; </code></pre> <p>Where I then use it like this:</p> <pre><code>MyIndexType myIndex; for( ... some loop ...) { myIndex[someId].push_back(someVal); } </code></pre> <p>If there was no entry in the map the code will insert a new empty vector and then append to it.</p> <p>In Python it would look like this:</p> <pre><code>myIndex = {} for (someId,someVal) in collection: try: myIndex[someId].append(someVal) except KeyError: myIndex[someId] = [someVal] </code></pre> <p>The try except is a bit ugly here. Is there a way to tell the dictionary an object type to insert when a KeyError is encountered at dictionary declaration time?</p>
9
2008-11-27T21:00:47Z
324,660
<p>How about this? It may not be performance-optimal, but I think it's the "simplest thing that could possibly work".</p> <pre><code>myIndex = {} for (someId,someVal) in collection: if someId not in myIndex: myIndex[someId] = [] myIndex[someId].append(someVal) </code></pre>
0
2008-11-27T21:14:37Z
[ "python", "dictionary" ]
What is the equivalent of map<int, vector<int> > in Python?
324,643
<p>In C++ often do something like this:</p> <pre><code>typedef map&lt;int, vector&lt;int&gt; &gt; MyIndexType; </code></pre> <p>Where I then use it like this:</p> <pre><code>MyIndexType myIndex; for( ... some loop ...) { myIndex[someId].push_back(someVal); } </code></pre> <p>If there was no entry in the map the code will insert a new empty vector and then append to it.</p> <p>In Python it would look like this:</p> <pre><code>myIndex = {} for (someId,someVal) in collection: try: myIndex[someId].append(someVal) except KeyError: myIndex[someId] = [someVal] </code></pre> <p>The try except is a bit ugly here. Is there a way to tell the dictionary an object type to insert when a KeyError is encountered at dictionary declaration time?</p>
9
2008-11-27T21:00:47Z
324,721
<p>Just to complete the answer by Alastair: There is also the <strong>get</strong> equivalent of <strong>setdefault</strong>, which is called <strong>get</strong> (and not getdefault, as one might think):</p> <pre><code>myIndex = {} someId = None myList = myIndex.get(someId, []) # myList is [] now </code></pre>
2
2008-11-27T22:04:32Z
[ "python", "dictionary" ]
What is the equivalent of map<int, vector<int> > in Python?
324,643
<p>In C++ often do something like this:</p> <pre><code>typedef map&lt;int, vector&lt;int&gt; &gt; MyIndexType; </code></pre> <p>Where I then use it like this:</p> <pre><code>MyIndexType myIndex; for( ... some loop ...) { myIndex[someId].push_back(someVal); } </code></pre> <p>If there was no entry in the map the code will insert a new empty vector and then append to it.</p> <p>In Python it would look like this:</p> <pre><code>myIndex = {} for (someId,someVal) in collection: try: myIndex[someId].append(someVal) except KeyError: myIndex[someId] = [someVal] </code></pre> <p>The try except is a bit ugly here. Is there a way to tell the dictionary an object type to insert when a KeyError is encountered at dictionary declaration time?</p>
9
2008-11-27T21:00:47Z
324,723
<p>From Python 2.5 and on you can get the behavior of setdefault or using defaultdict by implementing </p> <pre><code>__missing__(k) </code></pre> <p>as in note 10 <a href="http://www.python.org/doc/2.5.2/lib/typesmapping.html" rel="nofollow">here</a>.</p>
1
2008-11-27T22:12:21Z
[ "python", "dictionary" ]
Strategies for speeding up batch ORM operations in Django
324,779
<p>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:</p> <pre><code>for item in Something.objects.filter(x='y'): item.a="something" item.save() </code></pre> <p>Sometimes my filter criterion looks like "where x in ('a','b','c',...)".</p> <p>It seems the <a href="http://code.djangoproject.com/ticket/661">official answer to this is "won't fix"</a>. I'm wondering what strategies people are using to improve performance in these scenarios.</p>
9
2008-11-27T23:01:18Z
324,954
<p>You need to use transactions or create the sql statement by hand. You could also try using SQLAlchemy which supports a few great ORM features like Unit of Work (or application transaction).</p> <p>Django transactions: <a href="http://docs.djangoproject.com/en/dev/topics/db/transactions/?from=olddocs" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/transactions/?from=olddocs</a></p> <p>SQLAlchemy: <a href="http://www.sqlalchemy.org/" rel="nofollow">http://www.sqlalchemy.org/</a></p>
1
2008-11-28T02:05:22Z
[ "python", "django", "batch-file", "orm" ]
Strategies for speeding up batch ORM operations in Django
324,779
<p>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:</p> <pre><code>for item in Something.objects.filter(x='y'): item.a="something" item.save() </code></pre> <p>Sometimes my filter criterion looks like "where x in ('a','b','c',...)".</p> <p>It seems the <a href="http://code.djangoproject.com/ticket/661">official answer to this is "won't fix"</a>. I'm wondering what strategies people are using to improve performance in these scenarios.</p>
9
2008-11-27T23:01:18Z
325,066
<p>The ticket you linked to is for bulk creation - if you're not relying on an overridden <code>save</code> method or pre/post save signals to do bits of work on save, <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once"><code>QuerySet</code> has an <code>update</code> method</a> which you can use to perform an <code>UPDATE</code> on the filtered rows:</p> <pre><code>Something.objects.filter(x__in=['a', 'b', 'c']).update(a='something') </code></pre>
15
2008-11-28T04:39:02Z
[ "python", "django", "batch-file", "orm" ]
JDBC & MSSQL seem to be truncating large fields
324,945
<p>I'm using jython 2.2.1, and jdbc 1.2 and connecting to a mssql 2000 database, writing the contents of an email to it. When I get to the body of the email which can be quite large sometimes I need to truncate the data at 5000 chars. Except mssql &amp; jdbc gang up on me like school yard bullies, when i check the database loads of my data is missing, every time, with max chars = 256 chars.</p> <p>I have checked the size of the field and it is set to 5000. what gives? </p> <p>I am pretty sure it is related to jdbc, as the previous version used .... vb6 &amp; odbc, without a hitch.</p> <p>here is some code:</p> <pre><code>BODY_FIELD_DATABASE=5000 def _execute_insert(self): try: self._stmt=self._con.prepareStatement(\ "INSERT INTO EmailHdr (EntryID, MailSubject, MailFrom, MailTo, MailReceive, MailSent, AttachNo, MailBody)\ VALUES (?, ?, ?, ?, ?, ?, ?, cast(? as varchar (" + str(BODY_FIELD_DATABASE) + ")))") self._stmt.setString(1,self._emailEntryId) self._stmt.setString(2,self._subject) self._stmt.setString(3,self._fromWho) self._stmt.setString(4,self._toWho) self._stmt.setString(5,self._emailRecv) self._stmt.setString(6,self._emailSent) self._stmt.setString(7,str(int(self._attachmentCount) + 1)) self._stmt.setString(8,self._format_email_body()) self._stmt.execute() self._prepare_inserting_attachment_data() self._insert_attachment_data() except: raise def _format_email_body(self): if not self._emailBody: return " " if len(self._emailBody) &gt; BODY_FIELD_DATABASE: return self._clean_body(self._emailBody[:BODY_FIELD_DATABASE]) else: return self._clean_body(self._emailBody) def _clean_body(self,dirty): '''used to clean =20 occurrence in email body that contains chinese characters http://en.wikipedia.org/wiki/Quoted-printable''' dirty=str(dirty) return dirty.replace(r"=20","") </code></pre>
1
2008-11-28T01:58:14Z
324,952
<p>Deleted my answer - it was totally wrong. Keeping it here though so comments &amp; conversation hang around.</p> <p><strong>EDIT:</strong></p> <p>As you can read in the comments, here's what happened:</p> <p>The data was being put into the database fine, but the MSSQL Query Manager could not display the Chinese characters.</p>
0
2008-11-28T02:03:08Z
[ "python", "sql-server", "jdbc", "jython" ]
How do I determine if an email is Base64 encoded?
324,980
<p>I am having difficulty determining if the body of a text email message is base64 encoded. if it is then use this line of code; making use of jython 2.2.1</p> <pre><code>dirty=base64.decodestring(dirty) </code></pre> <p>else continue as normal.</p> <p>This is the code I have atm. What line of code will allow me to extract this from the email: </p> <p>"Content-Transfer-Encoding: base64" </p> <pre><code>import email, email.Message import base64 def _get_email_body(self): try: parts=self._email.get_payload() check=parts[0].get_content_type() if check=="text/plain": part=parts[0].get_payload() enc = part[0]['Content-Transfer-Encoding'] if enc == "base64": dirty=base64.decodestring(dirty) elif check=="multipart/alternative": part=parts[0].get_payload() enc = part[0]['Content-Transfer-Encoding'] if part[0].get_content_type()=="text/plain": dirty=part[0].get_payload() if enc == "base64": dirty=base64.decodestring(dirty) else: return "cannot obtain the body of the email" else: return "cannot obtain the body of the email" return dirty except: raise </code></pre> <p>OKAY this code works now! thanks all</p>
4
2008-11-28T02:30:50Z
324,989
<p>Try:</p> <pre><code>enc = msg['Content-Transfer-Encoding'] </code></pre> <p>It's a header so you won't be able to get it looking at the body. You should be able to get at the same place you find out the Subject.</p>
4
2008-11-28T02:44:04Z
[ "python", "email", "encoding", "jython", "email-headers" ]
Launch a shell command with in a python script, wait for the termination and return to the script
325,463
<p>I've a python script that has to launch a shell command for every file in a dir:</p> <pre><code>import os files = os.listdir(".") for f in files: os.execlp("myscript", "myscript", f) </code></pre> <p>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 script.</p> <p>How can I do? Do I have to <code>fork()</code> before <code>calling os.execlp()</code>?</p>
32
2008-11-28T10:42:03Z
325,467
<p>The <code>os.exec*()</code> functions <em>replace</em> the current programm with the new one. When this programm ends so does your process. You probably want <code>os.system()</code>.</p>
7
2008-11-28T10:45:23Z
[ "python", "subprocess", "popen", "os.execl" ]
Launch a shell command with in a python script, wait for the termination and return to the script
325,463
<p>I've a python script that has to launch a shell command for every file in a dir:</p> <pre><code>import os files = os.listdir(".") for f in files: os.execlp("myscript", "myscript", f) </code></pre> <p>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 script.</p> <p>How can I do? Do I have to <code>fork()</code> before <code>calling os.execlp()</code>?</p>
32
2008-11-28T10:42:03Z
325,474
<blockquote> <p>subprocess: The <code>subprocess</code> module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.</p> </blockquote> <p><a href="http://docs.python.org/library/subprocess.html">http://docs.python.org/library/subprocess.html</a></p> <p>Usage:</p> <pre><code>import subprocess process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) process.wait() print process.returncode </code></pre>
55
2008-11-28T10:48:18Z
[ "python", "subprocess", "popen", "os.execl" ]
Launch a shell command with in a python script, wait for the termination and return to the script
325,463
<p>I've a python script that has to launch a shell command for every file in a dir:</p> <pre><code>import os files = os.listdir(".") for f in files: os.execlp("myscript", "myscript", f) </code></pre> <p>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 script.</p> <p>How can I do? Do I have to <code>fork()</code> before <code>calling os.execlp()</code>?</p>
32
2008-11-28T10:42:03Z
325,488
<p>use spawn</p> <pre><code>import os os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') </code></pre>
2
2008-11-28T10:58:10Z
[ "python", "subprocess", "popen", "os.execl" ]
Launch a shell command with in a python script, wait for the termination and return to the script
325,463
<p>I've a python script that has to launch a shell command for every file in a dir:</p> <pre><code>import os files = os.listdir(".") for f in files: os.execlp("myscript", "myscript", f) </code></pre> <p>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 script.</p> <p>How can I do? Do I have to <code>fork()</code> before <code>calling os.execlp()</code>?</p>
32
2008-11-28T10:42:03Z
325,495
<p>You can use <a href="http://docs.python.org/library/subprocess.html"><code>subprocess.Popen</code></a>. There's a few ways to do it:</p> <pre><code>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 </code></pre> <p>Or, if you don't care what the external program actually does:</p> <pre><code>cmd = ['/run/myscript', '--arg', 'value'] subprocess.Popen(cmd).wait() </code></pre>
39
2008-11-28T11:01:45Z
[ "python", "subprocess", "popen", "os.execl" ]
Launch a shell command with in a python script, wait for the termination and return to the script
325,463
<p>I've a python script that has to launch a shell command for every file in a dir:</p> <pre><code>import os files = os.listdir(".") for f in files: os.execlp("myscript", "myscript", f) </code></pre> <p>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 script.</p> <p>How can I do? Do I have to <code>fork()</code> before <code>calling os.execlp()</code>?</p>
32
2008-11-28T10:42:03Z
5,184,921
<p>The subprocess module has come along way since 2008. In particular <a href="http://docs.python.org/library/subprocess.html#subprocess.check_call"><code>check_call</code></a> and <a href="http://docs.python.org/library/subprocess.html#subprocess.check_output"><code>check_output</code></a> make simple subprocess stuff even easier. The <code>check_*</code> family of functions are nice it that they raise an exception if something goes wrong.</p> <pre><code>import os import subprocess files = os.listdir('.') for f in files: subprocess.check_call( [ 'myscript', f ] ) </code></pre> <p>Any output generated by <code>myscript</code> will display as though your process produced the output (technically <code>myscript</code> and your python script share the same stdout). There are a couple of ways to avoid this.</p> <ul> <li><code>check_call( [ 'myscript', f ], stdout=subprocess.PIPE )</code><br> The stdout will be supressed (beware if <code>myscript</code> produces more that 4k of output). stderr will still be shown unless you add the option <code>stderr=subprocess.PIPE</code>.</li> <li><code>check_output( [ 'myscript', f ] )</code><br> <code>check_output</code> returns the stdout as a string so it isnt shown. stderr is still shown unless you add the option <code>stderr=subprocess.STDOUT</code>.</li> </ul>
9
2011-03-03T18:29:29Z
[ "python", "subprocess", "popen", "os.execl" ]
Packaging a Python library
326,254
<p>I have a few Munin plugins which report stats from an Autonomy database. They all use a small library which scrapes the XML status output for the relevant numbers.</p> <p>I'm trying to bundle the library and plugins into a Puppet-installable RPM. The actual RPM-building should be straightforward; once I have a <code>distutils</code>-produced distfile I can make it into an RPM based on a .spec file pinched from the Dag or EPEL repos [1]. It's the <code>distutils</code> bit I'm unsure of -- in fact I'm not even sure my library is correctly written for packaging. Here's how it works:</p> <p>idol7stats.py:</p> <pre><code>import datetime import os import stat import sys import time import urllib import xml.sax class IDOL7Stats: cache_dir = '/tmp' def __init__(self, host, port): self.host = host self.port = port # ... def collect(self): self.data = self.__parseXML(self.__getXML()) def total_slots(self): return self.data['Service:Documents:TotalSlots'] </code></pre> <p>Plugin code:</p> <pre><code>from idol7stats import IDOL7Stats a = IDOL7Stats('db.example.com', 23113) a.collect() print a.total_slots() </code></pre> <p>I guess I want idol7stats.py to wind up in <code>/usr/lib/python2.4/site-packages/idol7stats</code>, or something else in Python's search path. What <code>distutils</code> magic do I need? This:</p> <pre><code>from distutils.core import setup setup(name = 'idol7stats', author = 'Me', author_email = '[email protected]', version = '0.1', py_modules = ['idol7stats']) </code></pre> <p>almost works, except the code goes in <code>/usr/lib/python2.4/site-packages/idol7stats.py</code>, not a subdirectory. I expect this is down to my not understanding the difference between modules/packages/other containers in Python.</p> <p>So, what's the rub?</p> <p>[1] Yeah, I could just plonk the library in <code>/usr/lib/python2.4/site-packages</code> using RPM but I want to know how to package Python code.</p>
4
2008-11-28T17:19:08Z
326,275
<p>You need to create a <em>package</em> to do what you want. You'd need a directory named <code>idol7stats</code> containing a file called <code>__init__.py</code> and any other library modules to package. Also, this will affect your scripts' imports; if you put <code>idol7stats.py</code> in a package called <code>idol7stats</code>, then your scripts need to "<code>import idol7stats.idol7stats</code>".</p> <p>To avoid that, you could just rename <code>idol7stats.py</code> to <code>idol7stats/__init__.py</code>, or you could put this line into <code>idol7stats/__init__.py</code> to "massage" the imports into the way you expect them:</p> <pre><code>from idol7stats.idol7stats import * </code></pre>
2
2008-11-28T17:30:40Z
[ "python", "packaging", "distutils" ]
Best language choice for a spam detection service
326,401
<p>I have around 20 or so active blogs that get quite a bit of spam. As I hate CAPCHA the alternative is very smart spam filtering. I want to build a simple REST api like spam checking service which I would use in all my blogs. That way I can consolidate IP blocks and offload spam detection to 3rd party such as <a href="http://akisment.com" rel="nofollow" title="Akisment">Akisment</a>, <a href="http://mollom.com/" rel="nofollow" title="Mollom">Mollom</a>, <a href="http://defensio.com/" rel="nofollow" title="Defensio">Defensio</a> and sometime in the future write my own spam detection to really get my head into some very interesting spam detection algorithms. </p> <p>My language of choice is PHP, I consider myself quite proficient and I can really dig in deep and come out with a solution. This project, I feel, can be used as a good exercise to learn another language. The big 2 that come to mind are Python and Ruby on Rails as everyone talks about them like its the next coming of our savior. Since this is mostly just an API and has no admin or public facing anything, seems like basic Python running a simple http server seems like the way to go. Am I missing anything? What would you, the great community, recommend? I would love to hear your language, book and best practices recommendations. </p> <p>This has to scale and I want to write it with that in mind. Right now I'd probably be able to use 3rd party's free plans, but soon enough I'd have to expand the whole thing to actually think on its own. For now I think I'll just store everything in a MySQL database until I can do some real analysis on it. Thanks!</p>
1
2008-11-28T18:37:52Z
326,462
<p>My first question - <strong>why don't you just use one of those three services you listed?</strong> It seems they do exactly what you want. Sorry for being cynical, but I doubt that you working alone could in a reasonable amount of time beat the software engineers designing the algorithms used at those websites, especially considering their source of income depends on how well they do it.</p> <p>Then again, you might just be smarter than they are =P. I'm not one to judge. In any case, I'd recommend <strong>python</strong>, for the reasons you stated - you won't need a fancy public interface, so python's lack of excellence in this area won't matter. Python is also good for doing text processing, and it has great built-in bindings for using databases (sqlite, for example; you can, of course, install MySQL if you feel it is necessary). </p> <p>Downsides: it might get a bit slow, depending on how sophisticated your algorithms get.</p>
9
2008-11-28T19:07:23Z
[ "php", "python", "mysql", "ruby", "spam-prevention" ]
Best language choice for a spam detection service
326,401
<p>I have around 20 or so active blogs that get quite a bit of spam. As I hate CAPCHA the alternative is very smart spam filtering. I want to build a simple REST api like spam checking service which I would use in all my blogs. That way I can consolidate IP blocks and offload spam detection to 3rd party such as <a href="http://akisment.com" rel="nofollow" title="Akisment">Akisment</a>, <a href="http://mollom.com/" rel="nofollow" title="Mollom">Mollom</a>, <a href="http://defensio.com/" rel="nofollow" title="Defensio">Defensio</a> and sometime in the future write my own spam detection to really get my head into some very interesting spam detection algorithms. </p> <p>My language of choice is PHP, I consider myself quite proficient and I can really dig in deep and come out with a solution. This project, I feel, can be used as a good exercise to learn another language. The big 2 that come to mind are Python and Ruby on Rails as everyone talks about them like its the next coming of our savior. Since this is mostly just an API and has no admin or public facing anything, seems like basic Python running a simple http server seems like the way to go. Am I missing anything? What would you, the great community, recommend? I would love to hear your language, book and best practices recommendations. </p> <p>This has to scale and I want to write it with that in mind. Right now I'd probably be able to use 3rd party's free plans, but soon enough I'd have to expand the whole thing to actually think on its own. For now I think I'll just store everything in a MySQL database until I can do some real analysis on it. Thanks!</p>
1
2008-11-28T18:37:52Z
326,537
<p>Python has some advantages.</p> <ol> <li><p>There are several HTTP server frameworks in Python. Look at the <a href="http://www.python.org/doc/2.5.2/lib/module-wsgiref.html" rel="nofollow">WSGI reference implementation</a>, and learn how to use the WSGI standard to handle web requests. It's very clean and extensible. It takes a little bit of study to see that WSGI is all about adding details to the request until you reach a stage in the processing where it's time to formulate a reply. </p></li> <li><p><a href="http://www.python.org/doc/2.5.2/lib/module-email.html" rel="nofollow">MIME email parsing</a> is pretty straightforward.</p></li> <li><p>After that, you'll be using site blacklisting and content filtering for your spam detection. </p> <ul> <li><p>A site blacklist can be a big, fancy RDBMS. Or it can be simple pickled Python Set of domain names and IP addresses. I recommend a simple pickled set object that lives in memory. It's fast. You can have your RESTful service reload this set from a source file on receipt of some GET request that forces a refresh.</p></li> <li><p>Text filtering is just hard. I'd start with <a href="http://spambayes.sourceforge.net/" rel="nofollow">SpamBayes</a>.</p></li> </ul></li> </ol>
2
2008-11-28T20:00:30Z
[ "php", "python", "mysql", "ruby", "spam-prevention" ]
Best language choice for a spam detection service
326,401
<p>I have around 20 or so active blogs that get quite a bit of spam. As I hate CAPCHA the alternative is very smart spam filtering. I want to build a simple REST api like spam checking service which I would use in all my blogs. That way I can consolidate IP blocks and offload spam detection to 3rd party such as <a href="http://akisment.com" rel="nofollow" title="Akisment">Akisment</a>, <a href="http://mollom.com/" rel="nofollow" title="Mollom">Mollom</a>, <a href="http://defensio.com/" rel="nofollow" title="Defensio">Defensio</a> and sometime in the future write my own spam detection to really get my head into some very interesting spam detection algorithms. </p> <p>My language of choice is PHP, I consider myself quite proficient and I can really dig in deep and come out with a solution. This project, I feel, can be used as a good exercise to learn another language. The big 2 that come to mind are Python and Ruby on Rails as everyone talks about them like its the next coming of our savior. Since this is mostly just an API and has no admin or public facing anything, seems like basic Python running a simple http server seems like the way to go. Am I missing anything? What would you, the great community, recommend? I would love to hear your language, book and best practices recommendations. </p> <p>This has to scale and I want to write it with that in mind. Right now I'd probably be able to use 3rd party's free plans, but soon enough I'd have to expand the whole thing to actually think on its own. For now I think I'll just store everything in a MySQL database until I can do some real analysis on it. Thanks!</p>
1
2008-11-28T18:37:52Z
326,562
<p>I humbly recommend <a href="http://www.lua.org" rel="nofollow">Lua</a>, not only because it's a great, fast language, already integrated with web servers, but also because you can then exploit <a href="http://osbf-lua.luaforge.net/" rel="nofollow">OSBF-Lua</a>, an existing spam filter that has won spam-filtering competitions for several years in a row. Fidelis Assis and I have put in a lot of work trying to generalize the model beyond email, and we'd be delighted to work with you on integrating it with your app, which is what Lua was designed for.</p> <p>As for scaling, in training mode we process hundreds of emails per second on a 2006 machine, so that should work out pretty well even for a busy web site.</p> <p>We'd need to work with you on classifying stuff without mail headers, but I've been pushing in that direction already. For more info please write [email protected]. (Yes, I <em>want</em> people to send me spam. It's for research!)</p>
1
2008-11-28T20:15:35Z
[ "php", "python", "mysql", "ruby", "spam-prevention" ]
Best language choice for a spam detection service
326,401
<p>I have around 20 or so active blogs that get quite a bit of spam. As I hate CAPCHA the alternative is very smart spam filtering. I want to build a simple REST api like spam checking service which I would use in all my blogs. That way I can consolidate IP blocks and offload spam detection to 3rd party such as <a href="http://akisment.com" rel="nofollow" title="Akisment">Akisment</a>, <a href="http://mollom.com/" rel="nofollow" title="Mollom">Mollom</a>, <a href="http://defensio.com/" rel="nofollow" title="Defensio">Defensio</a> and sometime in the future write my own spam detection to really get my head into some very interesting spam detection algorithms. </p> <p>My language of choice is PHP, I consider myself quite proficient and I can really dig in deep and come out with a solution. This project, I feel, can be used as a good exercise to learn another language. The big 2 that come to mind are Python and Ruby on Rails as everyone talks about them like its the next coming of our savior. Since this is mostly just an API and has no admin or public facing anything, seems like basic Python running a simple http server seems like the way to go. Am I missing anything? What would you, the great community, recommend? I would love to hear your language, book and best practices recommendations. </p> <p>This has to scale and I want to write it with that in mind. Right now I'd probably be able to use 3rd party's free plans, but soon enough I'd have to expand the whole thing to actually think on its own. For now I think I'll just store everything in a MySQL database until I can do some real analysis on it. Thanks!</p>
1
2008-11-28T18:37:52Z
327,084
<p>I'd have to recommend Akismet for it's ease-of-use and high accuracy. With only a WordPress.com API key and an API call, you can determine if a given blob of text from a user is spammy. I've been using the Akismet plugin for WordPress, which uses the same API, and have had stellar results with it for the last year or so.</p> <p>Zend Framework has a great Akismet PHP class you can use independent of the rest of the framework, which should make integration pretty straightforward. Documentation is quite thorough, as well.</p>
1
2008-11-29T02:50:48Z
[ "php", "python", "mysql", "ruby", "spam-prevention" ]
Converting a string of 1's and 0's to a byte array
326,571
<p>I have a string with a length that is a multiple of 8 that contains only 0's and 1's. I want to convert the string into a byte array suitable for writing to a file. For instance, if I have the string "0010011010011101", I want to get the byte array [0x26, 0x9d], which, when written to file, will give 0x269d as the binary (raw) contents.</p> <p>How can I do this in Python?</p>
4
2008-11-28T20:17:22Z
326,587
<p>You could do something like this:</p> <pre><code>&gt;&gt;&gt; s = "0010011010011101" &gt;&gt;&gt; [int(s[x:x+8], 2) for x in range(0, len(s), 8)] [38, 157] </code></pre>
5
2008-11-28T20:24:39Z
[ "python" ]
Converting a string of 1's and 0's to a byte array
326,571
<p>I have a string with a length that is a multiple of 8 that contains only 0's and 1's. I want to convert the string into a byte array suitable for writing to a file. For instance, if I have the string "0010011010011101", I want to get the byte array [0x26, 0x9d], which, when written to file, will give 0x269d as the binary (raw) contents.</p> <p>How can I do this in Python?</p>
4
2008-11-28T20:17:22Z
326,594
<pre><code>py&gt; data = "0010011010011101" py&gt; data = [data[8*i:8*(i+1)] for i in range(len(data)/8)] py&gt; data ['00100110', '10011101'] py&gt; data = [int(i, 2) for i in data] py&gt; data [38, 157] py&gt; data = ''.join(chr(i) for i in data) py&gt; data '&amp;\x9d' </code></pre>
3
2008-11-28T20:26:19Z
[ "python" ]
Converting a string of 1's and 0's to a byte array
326,571
<p>I have a string with a length that is a multiple of 8 that contains only 0's and 1's. I want to convert the string into a byte array suitable for writing to a file. For instance, if I have the string "0010011010011101", I want to get the byte array [0x26, 0x9d], which, when written to file, will give 0x269d as the binary (raw) contents.</p> <p>How can I do this in Python?</p>
4
2008-11-28T20:17:22Z
326,614
<p>Your question shows a sequence of integers, but says "array of bytes" and also says "when written to file, will give 0x269d as the binary (raw) contents". These are three very different things. I think you've over-specified. From your various comments it looks like you only want the file output, and the other descriptions were not what you wanted.</p> <p>If you want a sequence of integers, look at Greg Hewgill's answer.</p> <p>If you want a sequence of bytes (as in a string) -- which can be written to a file -- look at Martin v. Löwis answer.</p> <p>If you wanted an array of bytes, you have to do this.</p> <pre><code>import array intList= [int(s[x:x+8], 2) for x in range(0, len(s), 8)] byteArray= array.array('B', intList) </code></pre>
4
2008-11-28T20:34:03Z
[ "python" ]
How can I dynamically get the set of classes from the current python module?
326,770
<p>I have a python module that defines a number of classes:</p> <pre><code>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" </code></pre> <p>From within the module, how might I add an attribute that gives me all of the classes?</p> <p>dir() gives me the names of everything from within my module, but I can't seem to figure out how to go from the name of a class to the class itself from <em>within</em> the module.</p> <p>From outside of the module, I can simply use <code>getattr(mod, 'A')</code>, but I don't have a <code>self</code> kind of module from within the module itself.</p> <p>This seems pretty obvious. Can someone tell me what I'm missing?</p>
5
2008-11-28T22:07:18Z
326,789
<pre><code>import sys getattr(sys.modules[__name__], 'A') </code></pre>
9
2008-11-28T22:16:19Z
[ "python", "reflection", "metaprogramming" ]
How can I dynamically get the set of classes from the current python module?
326,770
<p>I have a python module that defines a number of classes:</p> <pre><code>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" </code></pre> <p>From within the module, how might I add an attribute that gives me all of the classes?</p> <p>dir() gives me the names of everything from within my module, but I can't seem to figure out how to go from the name of a class to the class itself from <em>within</em> the module.</p> <p>From outside of the module, I can simply use <code>getattr(mod, 'A')</code>, but I don't have a <code>self</code> kind of module from within the module itself.</p> <p>This seems pretty obvious. Can someone tell me what I'm missing?</p>
5
2008-11-28T22:07:18Z
326,796
<p>You can smash this into one for statement, but that'd have messy code duplication.</p> <pre><code>import sys import types this_module = sys.modules[__name__] [x for x in [getattr(this_module, x) for x in dir(this_module)] if type(x) == types.ClassType] </code></pre>
5
2008-11-28T22:20:10Z
[ "python", "reflection", "metaprogramming" ]
How can I dynamically get the set of classes from the current python module?
326,770
<p>I have a python module that defines a number of classes:</p> <pre><code>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" </code></pre> <p>From within the module, how might I add an attribute that gives me all of the classes?</p> <p>dir() gives me the names of everything from within my module, but I can't seem to figure out how to go from the name of a class to the class itself from <em>within</em> the module.</p> <p>From outside of the module, I can simply use <code>getattr(mod, 'A')</code>, but I don't have a <code>self</code> kind of module from within the module itself.</p> <p>This seems pretty obvious. Can someone tell me what I'm missing?</p>
5
2008-11-28T22:07:18Z
326,881
<pre> classes = [x for x in globals().values() if isinstance(x, type)] </pre>
2
2008-11-28T23:17:31Z
[ "python", "reflection", "metaprogramming" ]
Something similar to PHP's SimpleXML in Python?
326,794
<p>Is there a way in Python to handle XML files similar to the way PHP's SimpleXML extension does them?</p> <p>Ideally I just want to be able to access certain xml datas from a list object.</p>
7
2008-11-28T22:19:06Z
326,806
<p>There is a long list of libraries associated with XML processing on the <a href="http://wiki.python.org/moin/PythonXml" rel="nofollow">Python wiki</a>. Note that a number of them are included in the standard library. Most of them will do what you are looking for:</p> <blockquote> <p>to access certain xml datas from a list object</p> </blockquote> <p>which is a bit vague, and perhaps some more concrete use-case might narrow down that list for you.</p>
2
2008-11-28T22:26:08Z
[ "php", "python", "xml", "simplexml" ]
Something similar to PHP's SimpleXML in Python?
326,794
<p>Is there a way in Python to handle XML files similar to the way PHP's SimpleXML extension does them?</p> <p>Ideally I just want to be able to access certain xml datas from a list object.</p>
7
2008-11-28T22:19:06Z
3,646,509
<p>You might be referring to something like this:</p> <p><a href="http://github.com/joestump/python-simplexml" rel="nofollow">http://github.com/joestump/python-simplexml</a></p> <p>I haven't used it myself, but I was also looking for something like simplexml in PHP and this link showed up.</p>
1
2010-09-05T15:05:48Z
[ "php", "python", "xml", "simplexml" ]
Something similar to PHP's SimpleXML in Python?
326,794
<p>Is there a way in Python to handle XML files similar to the way PHP's SimpleXML extension does them?</p> <p>Ideally I just want to be able to access certain xml datas from a list object.</p>
7
2008-11-28T22:19:06Z
3,724,773
<p>You might want to try <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="nofollow">xml.etree.ElementTree</a> It provides many easy ways to access read xml and to build new xml. </p> <p>Or better yet use <a href="http://codespeak.net/lxml/tutorial.html" rel="nofollow">lxml.etree</a> that provides even more convenient ways of accessing the nodes (such as xpath)</p>
2
2010-09-16T08:01:32Z
[ "php", "python", "xml", "simplexml" ]
Something similar to PHP's SimpleXML in Python?
326,794
<p>Is there a way in Python to handle XML files similar to the way PHP's SimpleXML extension does them?</p> <p>Ideally I just want to be able to access certain xml datas from a list object.</p>
7
2008-11-28T22:19:06Z
9,926,389
<p><a href="http://lxml.de/objectify.html" rel="nofollow">lxml.objectify</a> does exactly what you want</p> <pre><code>In [1]: from lxml import objectify In [2]: x = objectify.fromstring("""&lt;response&gt;&lt;version&gt;1.2&lt;/version&gt;&lt;amount&gt;1.01&lt;/amount&gt;&lt;currency&gt;USD&lt;/currency&gt;&lt;/response&gt;""") In [3]: x.version Out[3]: 1.2 In [4]: x.amount Out[4]: 1.01 In [5]: x.currency Out[5]: 'USD' </code></pre>
0
2012-03-29T13:30:23Z
[ "php", "python", "xml", "simplexml" ]
Running unit tests on nested functions
326,910
<p>I come from the Java world, where you can hide variables and functions and then run unit tests against them using reflection. I have used nested functions to hide implementation details of my classes so that only the public API is visible. I am trying to write unit tests against these nested functions to make sure that I don't break them as I develop. I have tried calling one of the nested functions like:</p> <pre><code>def outer(): def inner(): pass outer.inner() </code></pre> <p>which results in the error message:</p> <blockquote> <p>AttributeError: 'function' object has no attribute 'inner'</p> </blockquote> <p>Is there a way for me to write unit tests against these nested functions? If not, is there a way to trigger the name munging for function names like you can for class variables by prefixing them with __?</p>
5
2008-11-28T23:41:40Z
326,912
<p>inner doesn't exist until outer makes it. You should either move inner up to a toplevel function for testability, or have the outer test test all the possible execution paths of itself and inner.</p> <p>Do note that the inner function isn't a simple function, it's a closure. Consider this case:</p> <pre><code>def outer(a): b = compute_something_from(a) def inner(): do_something_with(a, b) </code></pre> <p>That's the standard testability trade-off. If your <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity">cyclomatic complexity</a> is too high, your tests will be too numerous.</p>
6
2008-11-28T23:44:55Z
[ "python", "testing", "closures" ]
Running unit tests on nested functions
326,910
<p>I come from the Java world, where you can hide variables and functions and then run unit tests against them using reflection. I have used nested functions to hide implementation details of my classes so that only the public API is visible. I am trying to write unit tests against these nested functions to make sure that I don't break them as I develop. I have tried calling one of the nested functions like:</p> <pre><code>def outer(): def inner(): pass outer.inner() </code></pre> <p>which results in the error message:</p> <blockquote> <p>AttributeError: 'function' object has no attribute 'inner'</p> </blockquote> <p>Is there a way for me to write unit tests against these nested functions? If not, is there a way to trigger the name munging for function names like you can for class variables by prefixing them with __?</p>
5
2008-11-28T23:41:40Z
326,932
<p>The Python convention is to name "private" functions and methods with a leading underscore. When you see a leading underscore, you know not to try and use it.</p> <p>Remember, <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>.</p>
3
2008-11-29T00:04:42Z
[ "python", "testing", "closures" ]
Running unit tests on nested functions
326,910
<p>I come from the Java world, where you can hide variables and functions and then run unit tests against them using reflection. I have used nested functions to hide implementation details of my classes so that only the public API is visible. I am trying to write unit tests against these nested functions to make sure that I don't break them as I develop. I have tried calling one of the nested functions like:</p> <pre><code>def outer(): def inner(): pass outer.inner() </code></pre> <p>which results in the error message:</p> <blockquote> <p>AttributeError: 'function' object has no attribute 'inner'</p> </blockquote> <p>Is there a way for me to write unit tests against these nested functions? If not, is there a way to trigger the name munging for function names like you can for class variables by prefixing them with __?</p>
5
2008-11-28T23:41:40Z
326,956
<p>I don't think that there is any chance to access inner() from the extern namespace.</p> <p>However, in my opinion the fact that you keep inner() nested implies that the only "contract" that really matters is outer()'s one. inner() is part of the implementation, and you shouldn't want to test the implementation. If you really want to test inner(), do extensive tests on outer() with data that will involve all the functionalities of inner().</p>
2
2008-11-29T00:25:40Z
[ "python", "testing", "closures" ]
Running unit tests on nested functions
326,910
<p>I come from the Java world, where you can hide variables and functions and then run unit tests against them using reflection. I have used nested functions to hide implementation details of my classes so that only the public API is visible. I am trying to write unit tests against these nested functions to make sure that I don't break them as I develop. I have tried calling one of the nested functions like:</p> <pre><code>def outer(): def inner(): pass outer.inner() </code></pre> <p>which results in the error message:</p> <blockquote> <p>AttributeError: 'function' object has no attribute 'inner'</p> </blockquote> <p>Is there a way for me to write unit tests against these nested functions? If not, is there a way to trigger the name munging for function names like you can for class variables by prefixing them with __?</p>
5
2008-11-28T23:41:40Z
6,635,945
<p>No way to get inner function from outer function object (see the other replies!). Yet both unit tests and closures have made (for me at least) amazing developer performance improvements. Can we have both? Can we test nested functions in isolation?</p> <p>Not easily. </p> <p>However, such could seemingly be achieved with use of python modules parser, ast, or tokenizer to dice up the code itself, extracting inner functions (by some path through the nesting), and allowing tests to run them with state from enclosing functions (values for closed-over names) and stubs/mocks for more-nested functions (defined within the test target).</p> <p>Anybody know of anything like this? Googling failed to find anything.</p>
2
2011-07-09T16:12:27Z
[ "python", "testing", "closures" ]
Running unit tests on nested functions
326,910
<p>I come from the Java world, where you can hide variables and functions and then run unit tests against them using reflection. I have used nested functions to hide implementation details of my classes so that only the public API is visible. I am trying to write unit tests against these nested functions to make sure that I don't break them as I develop. I have tried calling one of the nested functions like:</p> <pre><code>def outer(): def inner(): pass outer.inner() </code></pre> <p>which results in the error message:</p> <blockquote> <p>AttributeError: 'function' object has no attribute 'inner'</p> </blockquote> <p>Is there a way for me to write unit tests against these nested functions? If not, is there a way to trigger the name munging for function names like you can for class variables by prefixing them with __?</p>
5
2008-11-28T23:41:40Z
37,897,092
<p>I had the same doubt and found a way to get tests going for inner functions.</p> <pre><code>def outer(): def inner(): pass if __debug__: test_inner(inner) # return def test_inner(f): f() # this calls the inner function outer() </code></pre> <p>Basically you can send the inner function as a parameter to the outside and test it as you wish. When calling <strong>outer()</strong>, your test will run, and since it's a closure, it will preserve any extra property from the outer function (like variables). Using a list, you can send as many functions as you wish. To ignore the <strong>if</strong>, an option is to run the code like that:</p> <pre><code>python -O code.py </code></pre>
0
2016-06-18T12:43:07Z
[ "python", "testing", "closures" ]
using curses with raw_input in python
326,922
<p>In my python linux console application I use curses to handle displaying of data. At the same time I'd like to have an input line to enter commands, pretty much in good ol' irssi-style. With default curses getch() I'd have to do a lot of coding just to get the basic funcionality of raw_input function - arrow keys to move cursor / browse through the input history.</p> <p>Is there a simple way to get such behavior working with curses, as it captures input events and I can't just use functions that read sys.stdin.</p>
4
2008-11-28T23:54:50Z
327,141
<p>Use curses.textpad</p> <p><a href="http://www.python.org/doc/2.4.1/lib/module-curses.textpad.html" rel="nofollow">http://www.python.org/doc/2.4.1/lib/module-curses.textpad.html</a></p>
1
2008-11-29T04:01:43Z
[ "python", "console-application", "ncurses" ]
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
<p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p> <p><b>UPDATE</b></p> <p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?</p> <p>I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.</p> <h3>My email:</h3> <blockquote> <p>There are at least 3 ways to do a square root in Python: math.sqrt, the '**' operator and pow(x,.5). I'm just curious as to the differences in the implementation of each of these. When it comes to efficiency which is better?</p> </blockquote> <h3>His response:</h3> <blockquote> <p>pow and ** are equivalent; math.sqrt doesn't work for complex numbers, and links to the C sqrt() function. As to which one is faster, I have no idea...</p> </blockquote>
116
2008-11-29T01:24:09Z
327,005
<p>Most likely math.sqrt(x), because it's optimized for square rooting.</p> <p>Benchmarks will provide you the answer you are looking for.</p>
4
2008-11-29T01:25:16Z
[ "python", "performance" ]
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
<p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p> <p><b>UPDATE</b></p> <p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?</p> <p>I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.</p> <h3>My email:</h3> <blockquote> <p>There are at least 3 ways to do a square root in Python: math.sqrt, the '**' operator and pow(x,.5). I'm just curious as to the differences in the implementation of each of these. When it comes to efficiency which is better?</p> </blockquote> <h3>His response:</h3> <blockquote> <p>pow and ** are equivalent; math.sqrt doesn't work for complex numbers, and links to the C sqrt() function. As to which one is faster, I have no idea...</p> </blockquote>
116
2008-11-29T01:24:09Z
327,009
<p>How many square roots are you really performing? Are you trying to write some 3D graphics engine in Python? If not, then why go with code which is cryptic over code that is easy to read? The time difference is would be less than anybody could notice in just about any application I could forsee. I really don't mean to put down your question, but it seems that you're going a little too far with premature optimization.</p>
13
2008-11-29T01:28:24Z
[ "python", "performance" ]
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
<p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p> <p><b>UPDATE</b></p> <p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?</p> <p>I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.</p> <h3>My email:</h3> <blockquote> <p>There are at least 3 ways to do a square root in Python: math.sqrt, the '**' operator and pow(x,.5). I'm just curious as to the differences in the implementation of each of these. When it comes to efficiency which is better?</p> </blockquote> <h3>His response:</h3> <blockquote> <p>pow and ** are equivalent; math.sqrt doesn't work for complex numbers, and links to the C sqrt() function. As to which one is faster, I have no idea...</p> </blockquote>
116
2008-11-29T01:24:09Z
327,011
<p>As per comments, I've updated the code:</p> <pre><code>import time import math def timeit1(): s = time.time() for i in xrange(750000): z=i**.5 print "Took %f seconds" % (time.time() - s) def timeit2(arg=math.sqrt): s = time.time() for i in xrange(750000): z=arg(i) print "Took %f seconds" % (time.time() - s) timeit1() timeit2() </code></pre> <p>Now the <code>math.sqrt</code> function is directly in a local argument, meaning it has the fastest lookup possible. </p> <p><strong>UPDATE:</strong> The python version seems to matter here. I used to think that <code>timeit1</code> would be faster, since when python parses "i**.5" it knows, syntactically, which method to call (<code>__pow__</code> or some variant), so it doesn't have to go through the overhead of lookup that the <code>math.sqrt</code> variant does. But I might be wrong:</p> <p><strong>Python 2.5:</strong> 0.191000 vs. 0.224000</p> <p><strong>Python 2.6:</strong> 0.195000 vs. 0.139000</p> <p>Also psyco seems to deal with <code>math.sqrt</code> better:</p> <p><strong>Python 2.5 + Psyco 2.0:</strong> 0.109000 vs. 0.043000</p> <p><strong>Python 2.6 + Psyco 2.0:</strong> 0.128000 vs. 0.067000</p> <hr> <pre><code>| Interpreter | x**.5, | sqrt, | sqrt faster, % | | | seconds | seconds | | |----------------+---------+---------+----------------| | Python 3.2rc1+ | 0.32 | 0.27 | 19 | | Python 3.1.2 | 0.136 | 0.088 | 55 | | Python 3.0.1 | 0.155 | 0.102 | 52 | | Python 2.7 | 0.132 | 0.079 | 67 | | Python 2.6.6 | 0.121 | 0.075 | 61 | | PyPy 1.4.1 | 0.083 | 0.0159 | 422 | | Jython 2.5.1 | 0.132 | 0.22 | -40 | | Python 2.5.5 | 0.129 | 0.125 | 3 | | Python 2.4.6 | 0.131 | 0.123 | 7 | #+TBLFM: $4=100*($2-$3)/$3;%.0f </code></pre> <p>Table results produced on machine:</p> <pre><code>$ uname -vms Linux #42-Ubuntu SMP Thu Dec 2 02:41:37 UTC 2010 x86_64 $ cat /proc/cpuinfo | grep 'model name' | head -1 model name : Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz </code></pre> <p>To reproduce results:</p> <ul> <li>get source: <a href="https://gist.github.com/783011"><code>git clone git://gist.github.com/783011.git gist-783011</code></a></li> <li>install <a href="http://codespeak.net/tox/"><code>tox</code></a>: <code>pip install tox</code></li> <li>run <code>tox</code> from the directory with <code>tox.ini</code> file.</li> </ul>
57
2008-11-29T01:32:11Z
[ "python", "performance" ]
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
<p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p> <p><b>UPDATE</b></p> <p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?</p> <p>I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.</p> <h3>My email:</h3> <blockquote> <p>There are at least 3 ways to do a square root in Python: math.sqrt, the '**' operator and pow(x,.5). I'm just curious as to the differences in the implementation of each of these. When it comes to efficiency which is better?</p> </blockquote> <h3>His response:</h3> <blockquote> <p>pow and ** are equivalent; math.sqrt doesn't work for complex numbers, and links to the C sqrt() function. As to which one is faster, I have no idea...</p> </blockquote>
116
2008-11-29T01:24:09Z
327,015
<p>You might want to benchmark the <a href="http://www.codemaestro.com/reviews/9" rel="nofollow">fast Newton-Raphson square root</a> as well. Shouldn't take much to convert to Python.</p>
0
2008-11-29T01:36:19Z
[ "python", "performance" ]
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
<p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p> <p><b>UPDATE</b></p> <p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?</p> <p>I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.</p> <h3>My email:</h3> <blockquote> <p>There are at least 3 ways to do a square root in Python: math.sqrt, the '**' operator and pow(x,.5). I'm just curious as to the differences in the implementation of each of these. When it comes to efficiency which is better?</p> </blockquote> <h3>His response:</h3> <blockquote> <p>pow and ** are equivalent; math.sqrt doesn't work for complex numbers, and links to the C sqrt() function. As to which one is faster, I have no idea...</p> </blockquote>
116
2008-11-29T01:24:09Z
327,024
<p>In these micro-benchmarks, math.sqrt will be slower, because of the slight time it takes to lookup the sqrt in the math namespace. You can improve it slightly with </p> <pre><code> from math import sqrt </code></pre> <p>Even then though, running a few variations through timeit, show a slight (4-5%) performance advantage for "x**.5"</p> <p>interestingly, doing</p> <pre><code> import math sqrt = math.sqrt </code></pre> <p>sped it up even more, to within 1% difference in speed, with very little statistical significance.</p> <p>I will repeat Kibbee, and say that this is probably a premature optimization.</p>
8
2008-11-29T01:45:49Z
[ "python", "performance" ]
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
<p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p> <p><b>UPDATE</b></p> <p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?</p> <p>I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.</p> <h3>My email:</h3> <blockquote> <p>There are at least 3 ways to do a square root in Python: math.sqrt, the '**' operator and pow(x,.5). I'm just curious as to the differences in the implementation of each of these. When it comes to efficiency which is better?</p> </blockquote> <h3>His response:</h3> <blockquote> <p>pow and ** are equivalent; math.sqrt doesn't work for complex numbers, and links to the C sqrt() function. As to which one is faster, I have no idea...</p> </blockquote>
116
2008-11-29T01:24:09Z
327,048
<ul> <li>first rule of optimization: <em>don't do it</em></li> <li>second rule: <em>don't do it</em>, yet</li> </ul> <p>Here's some timings (Python 2.5.2, Windows):</p> <pre><code>$ python -mtimeit -s"from math import sqrt; x = 123" "x**.5" 1000000 loops, best of 3: 0.445 usec per loop $ python -mtimeit -s"from math import sqrt; x = 123" "sqrt(x)" 1000000 loops, best of 3: 0.574 usec per loop $ python -mtimeit -s"import math; x = 123" "math.sqrt(x)" 1000000 loops, best of 3: 0.727 usec per loop </code></pre> <p>This test shows that <code>x**.5</code> is slightly faster than <code>sqrt(x)</code>.</p> <p>For the Python 3.0 the result is the opposite:</p> <pre><code>$ \Python30\python -mtimeit -s"from math import sqrt; x = 123" "x**.5" 1000000 loops, best of 3: 0.803 usec per loop $ \Python30\python -mtimeit -s"from math import sqrt; x = 123" "sqrt(x)" 1000000 loops, best of 3: 0.695 usec per loop $ \Python30\python -mtimeit -s"import math; x = 123" "math.sqrt(x)" 1000000 loops, best of 3: 0.761 usec per loop </code></pre> <p><code>math.sqrt(x)</code> is always faster than <code>x**.5</code> on another machine (Ubuntu, Python 2.6 and 3.1):</p> <pre><code>$ python -mtimeit -s"from math import sqrt; x = 123" "x**.5" 10000000 loops, best of 3: 0.173 usec per loop $ python -mtimeit -s"from math import sqrt; x = 123" "sqrt(x)" 10000000 loops, best of 3: 0.115 usec per loop $ python -mtimeit -s"import math; x = 123" "math.sqrt(x)" 10000000 loops, best of 3: 0.158 usec per loop $ python3.1 -mtimeit -s"from math import sqrt; x = 123" "x**.5" 10000000 loops, best of 3: 0.194 usec per loop $ python3.1 -mtimeit -s"from math import sqrt; x = 123" "sqrt(x)" 10000000 loops, best of 3: 0.123 usec per loop $ python3.1 -mtimeit -s"import math; x = 123" "math.sqrt(x)" 10000000 loops, best of 3: 0.157 usec per loop </code></pre>
13
2008-11-29T02:16:47Z
[ "python", "performance" ]
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
<p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p> <p><b>UPDATE</b></p> <p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?</p> <p>I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.</p> <h3>My email:</h3> <blockquote> <p>There are at least 3 ways to do a square root in Python: math.sqrt, the '**' operator and pow(x,.5). I'm just curious as to the differences in the implementation of each of these. When it comes to efficiency which is better?</p> </blockquote> <h3>His response:</h3> <blockquote> <p>pow and ** are equivalent; math.sqrt doesn't work for complex numbers, and links to the C sqrt() function. As to which one is faster, I have no idea...</p> </blockquote>
116
2008-11-29T01:24:09Z
327,049
<p>For what it's worth (see Jim's answer). On my machine, running python 2.5:</p> <pre><code>PS C:\&gt; python -m timeit -n 100000 10000**.5 100000 loops, best of 3: 0.0543 usec per loop PS C:\&gt; python -m timeit -n 100000 -s "import math" math.sqrt(10000) 100000 loops, best of 3: 0.162 usec per loop PS C:\&gt; python -m timeit -n 100000 -s "from math import sqrt" sqrt(10000) 100000 loops, best of 3: 0.0541 usec per loop </code></pre>
3
2008-11-29T02:17:09Z
[ "python", "performance" ]