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
list
How to reduce color palette with PIL
1,065,945
<p>I'm not sure how I would go about reducing the color palette of a PIL Image. I would like to reduce an image's palette to the 5 prominent colors found in that image. My overall goal is to do some basic color sampling.</p>
11
2009-06-30T20:43:32Z
1,067,168
<p>I assume you want to do something more sophisticated than <a href="http://effbot.org/imagingbook/imageops.htm#tag-ImageOps.posterize" rel="nofollow">posterize</a>. "Sampling" as you say, will take some finesse, as the 5 most common colors in the image are likely to be similar to one another. Maybe take a look at the 5 most separated peaks in a <a href="http://effbot.org/imagingbook/image.htm#tag-Image.Image.histogram" rel="nofollow">histogram</a>.</p>
1
2009-07-01T03:38:51Z
[ "python", "image", "colors", "python-imaging-library", "palette" ]
How to reduce color palette with PIL
1,065,945
<p>I'm not sure how I would go about reducing the color palette of a PIL Image. I would like to reduce an image's palette to the 5 prominent colors found in that image. My overall goal is to do some basic color sampling.</p>
11
2009-06-30T20:43:32Z
1,071,275
<p>The short answer is to use the <code>Image.quantize</code> method. For more info, see: <a href="http://stackoverflow.com/questions/236692/how-do-i-convert-any-image-to-a-4-color-paletted-image-using-the-python-imaging-l">How do I convert any image to a 4-color paletted image using the Python Imaging Library ?</a></p>
3
2009-07-01T20:38:53Z
[ "python", "image", "colors", "python-imaging-library", "palette" ]
How to reduce color palette with PIL
1,065,945
<p>I'm not sure how I would go about reducing the color palette of a PIL Image. I would like to reduce an image's palette to the 5 prominent colors found in that image. My overall goal is to do some basic color sampling.</p>
11
2009-06-30T20:43:32Z
1,074,680
<p>That's easy, just use the undocumented colors argument:</p> <pre><code>result = image.convert('P', palette=Image.ADAPTIVE, colors=5) </code></pre> <p>I'm using Image.ADAPTIVE to avoid dithering</p>
22
2009-07-02T14:22:06Z
[ "python", "image", "colors", "python-imaging-library", "palette" ]
Unable to understand a statement about customizing Python's Macro Syntax
1,065,966
<p><a href="http://stackoverflow.com/questions/454648/pythonic-macro-syntax">Cody</a> has been building a Pythonic Macro Syntax. He says</p> <blockquote> <p>These macros allow you to define completely custom syntax, from new constructs to new operators. There's no facility for doing this in Python as it stands.</p> </blockquote> <p>I am not sure what he means by</p> <ul> <li>new constructs to new operators: <strong>Does he refer to binary operators such as +, - and multiplication in Math?</strong> </li> <li>his main goal: <strong>Where do you benefit in customizing Python's macro syntax?</strong></li> </ul>
1
2009-06-30T20:46:45Z
1,066,027
<p>No doubt Cody refers to completely new operators that are not currently in Python, such as (I dunno) <code>^^</code> or <code>++</code> or <code>+*</code> and so on, whatever they might mean. And he's explicitly saying that the macro system lets you define a completely new syntax <em>for Python</em> (his question was about the syntax of the macro definitions themselves).</p> <p>Some people care burningly about syntax and for example would much prefer to see Python uses braces rather than group by indentation; but Python itself will never follow those people's preferences...:</p> <pre><code>&gt;&gt;&gt; from __future__ import braces File "&lt;stdin&gt;", line 1 SyntaxError: not a chance </code></pre> <p>So these people might obtain what they crave by defining a completely new syntax for Python through this macro system.</p> <p>Others might use it to define specific custom languages that mostly follow Python's general outlines but add special new keywords, let you call functions without using parentheses, and so on, and so forth.</p> <p>Whether that's a good thing, in fact, is an ancient, moot issue—but some languages such as Lisp have always had macros of such power, and many people who came to Python from Lisp, such as Peter Norvig, would probably be quite happy to get back that syntax-making power they used to have in Lisp but lack in Python.</p>
6
2009-06-30T20:56:42Z
[ "python", "syntax", "macros" ]
Export set of data in different formats
1,066,516
<p>I want to be able to display set of data differently according to url parameters.</p> <p>My URL looks like /page/{limit}/{offset}/{format}/. </p> <p>For example:</p> <pre><code>/page/20/0/xml/ - subset [0:20) in xml /page/100/20/json/ - subset [20:100) in json </code></pre> <p>Also I want to be able to do the same for csv, text, excel, pdf, html, etc...</p> <p>I have to be able to set different mimetypes and content-types for different formats. For <strong>XML</strong> should be <strong>application/xhtml+xml</strong>, for csv - <strong>text/plain</strong>, etc...</p> <p>In HTML mode I want to be able to pass this data into some template (I'm using Django).</p> <p>I'm planing to make set look like:</p> <pre><code>dataset = { "meta" : {"offset" : 15, "limit" : 10, "total" : 1000}, "columns" : {"name" : "Name", "status" : "Status", "creation_date" : "Creation Date"} "items" : [ {"name" : "John Smith", "status" : 1, "creation_date" : "2009-06-30 10:10:09"}, {"name" : "Joe The Plummer", "status" : 2, "creation_date" : "2009-06-30 10:10:09"} ] }; </code></pre> <p>and have output like this:</p> <p>CSV output:</p> <pre><code>Name, Status, Creation Date John Smith, 1, 2009-06-30 10:10:09 Joe The Plummer, 2, 2009-06-30 10:10:09 </code></pre> <p>XML output:</p> <pre><code>&lt;items&gt; &lt;item id="1"&gt; &lt;name&gt;John Smith&lt;/name&gt; &lt;status&gt;1&lt;/status&gt; &lt;creation_date&gt;2009-06-30 10:10:09&lt;/creation_date&gt; &lt;/item&gt; &lt;item id="2"&gt; &lt;name&gt;Joe The Plummer&lt;/name&gt; &lt;status&gt;2&lt;/status&gt; &lt;creation_date&gt;2009-06-30 10:10:09&lt;/creation_date&gt; &lt;/item&gt; &lt;/items&gt; </code></pre> <p>So I think to have implemented my own renderers for each type - like XMLRenderer, RSSRenderer, JSONRenderer, etc...</p> <pre><code>if format == "xml": context = XMLRenderer().render(data = dataset) return HttpResponse(content, mimetype="application/xhtml+xml") elif format == "json": context = JSONRenderer().render(data = dataset) return HttpResponse(content, mimetype="text/plain") elif format == "rss": context = RSSRenderer(title="Some long title here", link="/page/10/10/rss/").render(data = dataset) return HttpResponse(content, mimetype="application/xhtml+xml") # few more formats... else: return render_to_response(SOME_TEMPLATE, dataset) </code></pre> <p>Is it correct approach?</p>
1
2009-06-30T23:02:17Z
1,066,621
<p>Yes, that is a correct approach.</p>
0
2009-06-30T23:30:15Z
[ "python", "django", "rendering" ]
Export set of data in different formats
1,066,516
<p>I want to be able to display set of data differently according to url parameters.</p> <p>My URL looks like /page/{limit}/{offset}/{format}/. </p> <p>For example:</p> <pre><code>/page/20/0/xml/ - subset [0:20) in xml /page/100/20/json/ - subset [20:100) in json </code></pre> <p>Also I want to be able to do the same for csv, text, excel, pdf, html, etc...</p> <p>I have to be able to set different mimetypes and content-types for different formats. For <strong>XML</strong> should be <strong>application/xhtml+xml</strong>, for csv - <strong>text/plain</strong>, etc...</p> <p>In HTML mode I want to be able to pass this data into some template (I'm using Django).</p> <p>I'm planing to make set look like:</p> <pre><code>dataset = { "meta" : {"offset" : 15, "limit" : 10, "total" : 1000}, "columns" : {"name" : "Name", "status" : "Status", "creation_date" : "Creation Date"} "items" : [ {"name" : "John Smith", "status" : 1, "creation_date" : "2009-06-30 10:10:09"}, {"name" : "Joe The Plummer", "status" : 2, "creation_date" : "2009-06-30 10:10:09"} ] }; </code></pre> <p>and have output like this:</p> <p>CSV output:</p> <pre><code>Name, Status, Creation Date John Smith, 1, 2009-06-30 10:10:09 Joe The Plummer, 2, 2009-06-30 10:10:09 </code></pre> <p>XML output:</p> <pre><code>&lt;items&gt; &lt;item id="1"&gt; &lt;name&gt;John Smith&lt;/name&gt; &lt;status&gt;1&lt;/status&gt; &lt;creation_date&gt;2009-06-30 10:10:09&lt;/creation_date&gt; &lt;/item&gt; &lt;item id="2"&gt; &lt;name&gt;Joe The Plummer&lt;/name&gt; &lt;status&gt;2&lt;/status&gt; &lt;creation_date&gt;2009-06-30 10:10:09&lt;/creation_date&gt; &lt;/item&gt; &lt;/items&gt; </code></pre> <p>So I think to have implemented my own renderers for each type - like XMLRenderer, RSSRenderer, JSONRenderer, etc...</p> <pre><code>if format == "xml": context = XMLRenderer().render(data = dataset) return HttpResponse(content, mimetype="application/xhtml+xml") elif format == "json": context = JSONRenderer().render(data = dataset) return HttpResponse(content, mimetype="text/plain") elif format == "rss": context = RSSRenderer(title="Some long title here", link="/page/10/10/rss/").render(data = dataset) return HttpResponse(content, mimetype="application/xhtml+xml") # few more formats... else: return render_to_response(SOME_TEMPLATE, dataset) </code></pre> <p>Is it correct approach?</p>
1
2009-06-30T23:02:17Z
1,066,999
<p>I suggest having the renderer also know about the mimetype rather than hardcoding the latter in the code that calls the renderer -- better to concentrate format-specific knowledge in one place, so the calling code would be</p> <pre><code>content, mimetype = renderer().render(data=dataset) return HttpResponse(content, mimetype=mimetype) </code></pre> <p>also, this is a great opportunity for the Registry design pattern (most long trees of if/elif are, but one where you're essentially deciding just which object or class to use is perfect!-). So you either hardcode a dict:</p> <pre><code>format2renderer = dict( xml=XMLRenderer, rss=RSSRenderer, # ...etc... ) </code></pre> <p>or maybe even better make renderers registers themselves in the dict at startup, but that may be too advanced/hard to arrange. In either case, what you have before the calling snippet I just quoted would be just:</p> <pre><code>renderer = format2renderer.get(format) if renderer is not None: ... </code></pre> <p>and when <code>None</code> you may apply your default code. I find dict lookups and polymorphism SO much easier to maintain and enhance than if/elif trees!-)</p>
1
2009-07-01T02:12:10Z
[ "python", "django", "rendering" ]
Multiprocessing in python with more then 2 levels
1,066,710
<p>I want to do a program and want make a the spawn like this process -> n process -> n process</p> <p>can the second level spawn process with multiprocessing ? using multiprocessinf module of python 2.6</p> <p>thnx</p>
4
2009-07-01T00:01:35Z
1,066,747
<p>@<a href="#1066724" rel="nofollow">vilalian</a>'s answer is correct, but terse. Of course, it's hard to supply more information when your original question was vague.</p> <p>To expand a little, you'd have your original program spawn its <code>n</code> processes, but they'd be slightly different than the original in that you'd want them (each, if I understand your question) to spawn <code>n</code> more processes. You could accomplish this by either by having them run code similar to your original process, but that spawned new sets of programs that performed the task at hand, without further processing, or you could use the same code/entry point, just providing different arguments - something like</p> <pre><code>def main(level): if level == 0: do_work else: for i in range(n): spawn_process_that_runs_main(level-1) </code></pre> <p>and start it off with <code>level == 2</code></p>
3
2009-07-01T00:14:09Z
[ "python", "multiprocessing" ]
Multiprocessing in python with more then 2 levels
1,066,710
<p>I want to do a program and want make a the spawn like this process -> n process -> n process</p> <p>can the second level spawn process with multiprocessing ? using multiprocessinf module of python 2.6</p> <p>thnx</p>
4
2009-07-01T00:01:35Z
1,066,750
<p>Sure you can. Expecially if you are using fork to spawn child processes, they works as perfectly normal processes (like the father). Thread management is quite different, but you can also use "second level" sub-treading. </p> <p>Pay attention to not over-complicate your program, as example program with two level threads are normally unused.</p>
0
2009-07-01T00:15:06Z
[ "python", "multiprocessing" ]
Multiprocessing in python with more then 2 levels
1,066,710
<p>I want to do a program and want make a the spawn like this process -> n process -> n process</p> <p>can the second level spawn process with multiprocessing ? using multiprocessinf module of python 2.6</p> <p>thnx</p>
4
2009-07-01T00:01:35Z
1,068,763
<p>You can structure your app as a series of process pools communicating via Queues at any nested depth. Though it can get hairy pretty quick (probably due to the required context switching).</p> <p>It's not erlang though that's for sure.</p> <p>The docs on <a href="http://docs.python.org/dev/library/multiprocessing.html" rel="nofollow">multiprocessing</a> are extremely useful.</p> <p><a href="http://blog.sadphaeton.com/source-code-node/multiprocessing.html" rel="nofollow">Here</a>(little too much to drop in a comment) is some code I use to increase throughput in a program that updates my feeds. I have one process polling for feeds that need to fetched, that stuffs it's results in a queue that a Process Pool of 4 workers picks up those results and fetches the feeds, it's results(if any) are then put in a queue for a Process Pool to parse and put into a queue to shove back in the database. Done sequentially, this process would be really slow due to some sites taking their own sweet time to respond so most of the time the process was waiting on data from the internet and would only use one core. Under this process based model, I'm actually waiting on the database the most it seems and my NIC is saturated most of the time as well as all 4 cores are actually doing something. Your mileage may vary.</p>
0
2009-07-01T12:00:08Z
[ "python", "multiprocessing" ]
Multiprocessing in python with more then 2 levels
1,066,710
<p>I want to do a program and want make a the spawn like this process -> n process -> n process</p> <p>can the second level spawn process with multiprocessing ? using multiprocessinf module of python 2.6</p> <p>thnx</p>
4
2009-07-01T00:01:35Z
1,068,961
<p>Yes - but, you might run into an issue which would require the fix I committed to python trunk yesterday. See bug <a href="http://bugs.python.org/issue5313" rel="nofollow">http://bugs.python.org/issue5313</a></p>
1
2009-07-01T12:41:13Z
[ "python", "multiprocessing" ]
find length of sequences of identical values in a numpy array
1,066,758
<p>In a pylab program (which could probably be a matlab program as well) I have a numpy array of numbers representing distances: <code>d[t]</code> is the <em>distance</em> at time <code>t</code> (and the timespan of my data is <code>len(d)</code> time units).</p> <p>The events I'm interested in are when the distance is below a certain threshold, and I want to compute the duration of these events. It's easy to get an array of booleans with <code>b = d&lt;threshold</code>, and the problem comes down to computing the sequence of the lengths of the True-only words in <code>b</code>. But I do not know how to do that efficiently (i.e. using numpy primitives), and I resorted to walk the array and to do manual change detection (i.e. initialize counter when value goes from False to True, increase counter as long as value is True, and output the counter to the sequence when value goes back to False). But this is tremendously slow.</p> <p><b>How to efficienly detect that sort of sequences in numpy arrays ?</b></p> <p>Below is some python code that illustrates my problem : the fourth dot takes a very long time to appear (if not, increase the size of the array)</p> <pre><code>from pylab import * threshold = 7 print '.' d = 10*rand(10000000) print '.' b = d&lt;threshold print '.' durations=[] for i in xrange(len(b)): if b[i] and (i==0 or not b[i-1]): counter=1 if i&gt;0 and b[i-1] and b[i]: counter+=1 if (b[i-1] and not b[i]) or i==len(b)-1: durations.append(counter) print '.' </code></pre>
19
2009-07-01T00:19:18Z
1,066,780
<pre><code>durations = [] counter = 0 for bool in b: if bool: counter += 1 elif counter &gt; 0: durations.append(counter) counter = 0 if counter &gt; 0: durations.append(counter) </code></pre>
0
2009-07-01T00:31:02Z
[ "python", "matlab", "numpy", "matplotlib" ]
find length of sequences of identical values in a numpy array
1,066,758
<p>In a pylab program (which could probably be a matlab program as well) I have a numpy array of numbers representing distances: <code>d[t]</code> is the <em>distance</em> at time <code>t</code> (and the timespan of my data is <code>len(d)</code> time units).</p> <p>The events I'm interested in are when the distance is below a certain threshold, and I want to compute the duration of these events. It's easy to get an array of booleans with <code>b = d&lt;threshold</code>, and the problem comes down to computing the sequence of the lengths of the True-only words in <code>b</code>. But I do not know how to do that efficiently (i.e. using numpy primitives), and I resorted to walk the array and to do manual change detection (i.e. initialize counter when value goes from False to True, increase counter as long as value is True, and output the counter to the sequence when value goes back to False). But this is tremendously slow.</p> <p><b>How to efficienly detect that sort of sequences in numpy arrays ?</b></p> <p>Below is some python code that illustrates my problem : the fourth dot takes a very long time to appear (if not, increase the size of the array)</p> <pre><code>from pylab import * threshold = 7 print '.' d = 10*rand(10000000) print '.' b = d&lt;threshold print '.' durations=[] for i in xrange(len(b)): if b[i] and (i==0 or not b[i-1]): counter=1 if i&gt;0 and b[i-1] and b[i]: counter+=1 if (b[i-1] and not b[i]) or i==len(b)-1: durations.append(counter) print '.' </code></pre>
19
2009-07-01T00:19:18Z
1,066,838
<p>While not <code>numpy</code> primitives, <code>itertools</code> functions are often very fast, so do give this one a try (and measure times for various solutions including this one, of course):</p> <pre><code>def runs_of_ones(bits): for bit, group in itertools.groupby(bits): if bit: yield sum(group) </code></pre> <p>If you do need the values in a list, just can use list(runs_of_ones(bits)), of course; but maybe a list comprehension might be marginally faster still:</p> <pre><code>def runs_of_ones_list(bits): return [sum(g) for b, g in itertools.groupby(bits) if b] </code></pre> <p>Moving to "numpy-native" possibilities, what about:</p> <pre><code>def runs_of_ones_array(bits): # make sure all runs of ones are well-bounded bounded = numpy.hstack(([0], bits, [0])) # get 1 at run starts and -1 at run ends difs = numpy.diff(bounded) run_starts, = numpy.where(difs &gt; 0) run_ends, = numpy.where(difs &lt; 0) return run_ends - run_starts </code></pre> <p>Again: be sure to benchmark solutions against each others in realistic-for-you examples!</p>
22
2009-07-01T01:04:34Z
[ "python", "matlab", "numpy", "matplotlib" ]
find length of sequences of identical values in a numpy array
1,066,758
<p>In a pylab program (which could probably be a matlab program as well) I have a numpy array of numbers representing distances: <code>d[t]</code> is the <em>distance</em> at time <code>t</code> (and the timespan of my data is <code>len(d)</code> time units).</p> <p>The events I'm interested in are when the distance is below a certain threshold, and I want to compute the duration of these events. It's easy to get an array of booleans with <code>b = d&lt;threshold</code>, and the problem comes down to computing the sequence of the lengths of the True-only words in <code>b</code>. But I do not know how to do that efficiently (i.e. using numpy primitives), and I resorted to walk the array and to do manual change detection (i.e. initialize counter when value goes from False to True, increase counter as long as value is True, and output the counter to the sequence when value goes back to False). But this is tremendously slow.</p> <p><b>How to efficienly detect that sort of sequences in numpy arrays ?</b></p> <p>Below is some python code that illustrates my problem : the fourth dot takes a very long time to appear (if not, increase the size of the array)</p> <pre><code>from pylab import * threshold = 7 print '.' d = 10*rand(10000000) print '.' b = d&lt;threshold print '.' durations=[] for i in xrange(len(b)): if b[i] and (i==0 or not b[i-1]): counter=1 if i&gt;0 and b[i-1] and b[i]: counter+=1 if (b[i-1] and not b[i]) or i==len(b)-1: durations.append(counter) print '.' </code></pre>
19
2009-07-01T00:19:18Z
1,066,864
<p>Just in case anyone is curious (and since you mentioned MATLAB in passing), here's one way to solve it in MATLAB:</p> <pre><code>threshold = 7; d = 10*rand(1,100000); % Sample data b = diff([false (d &lt; threshold) false]); durations = find(b == -1)-find(b == 1); </code></pre> <p>I'm not too familiar with Python, but maybe this could help give you some ideas. =)</p>
5
2009-07-01T01:15:16Z
[ "python", "matlab", "numpy", "matplotlib" ]
find length of sequences of identical values in a numpy array
1,066,758
<p>In a pylab program (which could probably be a matlab program as well) I have a numpy array of numbers representing distances: <code>d[t]</code> is the <em>distance</em> at time <code>t</code> (and the timespan of my data is <code>len(d)</code> time units).</p> <p>The events I'm interested in are when the distance is below a certain threshold, and I want to compute the duration of these events. It's easy to get an array of booleans with <code>b = d&lt;threshold</code>, and the problem comes down to computing the sequence of the lengths of the True-only words in <code>b</code>. But I do not know how to do that efficiently (i.e. using numpy primitives), and I resorted to walk the array and to do manual change detection (i.e. initialize counter when value goes from False to True, increase counter as long as value is True, and output the counter to the sequence when value goes back to False). But this is tremendously slow.</p> <p><b>How to efficienly detect that sort of sequences in numpy arrays ?</b></p> <p>Below is some python code that illustrates my problem : the fourth dot takes a very long time to appear (if not, increase the size of the array)</p> <pre><code>from pylab import * threshold = 7 print '.' d = 10*rand(10000000) print '.' b = d&lt;threshold print '.' durations=[] for i in xrange(len(b)): if b[i] and (i==0 or not b[i-1]): counter=1 if i&gt;0 and b[i-1] and b[i]: counter+=1 if (b[i-1] and not b[i]) or i==len(b)-1: durations.append(counter) print '.' </code></pre>
19
2009-07-01T00:19:18Z
1,068,397
<p>Here is a solution using only arrays: it takes an array containing a sequence of bools and counts the length of the transitions.</p> <pre><code>&gt;&gt;&gt; from numpy import array, arange &gt;&gt;&gt; b = array([0,0,0,1,1,1,0,0,0,1,1,1,1,0,0], dtype=bool) &gt;&gt;&gt; sw = (b[:-1] ^ b[1:]); print sw [False False True False False True False False True False False False True False] &gt;&gt;&gt; isw = arange(len(sw))[sw]; print isw [ 2 5 8 12] &gt;&gt;&gt; lens = isw[1::2] - isw[::2]; print lens [3 4] </code></pre> <p><code>sw</code> contains a true where there is a switch, <code>isw</code> converts them in indexes. The items of isw are then subtracted pairwise in <code>lens</code>.</p> <p>Notice that if the sequence started with an 1 it would count the length of the 0s sequences: this can be fixed in the indexing to compute lens. Also, I have not tested corner cases such sequences of length 1.</p> <hr> <p>Full function that returns start positions and lengths of all <code>True</code>-subarrays. </p> <pre><code>import numpy as np def count_adjacent_true(arr): assert len(arr.shape) == 1 assert arr.dtype == np.bool if arr.size == 0: return np.empty(0, dtype=int), np.empty(0, dtype=int) sw = np.insert(arr[1:] ^ arr[:-1], [0, arr.shape[0]-1], values=True) swi = np.arange(sw.shape[0])[sw] offset = 0 if arr[0] else 1 lengths = swi[offset+1::2] - swi[offset:-1:2] return swi[offset:-1:2], lengths </code></pre> <p>Tested for different bool 1D-arrays (empty array; single/multiple elements; even/odd lengths; started with <code>True</code>/<code>False</code>; with only <code>True</code>/<code>False</code> elements).</p>
5
2009-07-01T10:32:35Z
[ "python", "matlab", "numpy", "matplotlib" ]
find length of sequences of identical values in a numpy array
1,066,758
<p>In a pylab program (which could probably be a matlab program as well) I have a numpy array of numbers representing distances: <code>d[t]</code> is the <em>distance</em> at time <code>t</code> (and the timespan of my data is <code>len(d)</code> time units).</p> <p>The events I'm interested in are when the distance is below a certain threshold, and I want to compute the duration of these events. It's easy to get an array of booleans with <code>b = d&lt;threshold</code>, and the problem comes down to computing the sequence of the lengths of the True-only words in <code>b</code>. But I do not know how to do that efficiently (i.e. using numpy primitives), and I resorted to walk the array and to do manual change detection (i.e. initialize counter when value goes from False to True, increase counter as long as value is True, and output the counter to the sequence when value goes back to False). But this is tremendously slow.</p> <p><b>How to efficienly detect that sort of sequences in numpy arrays ?</b></p> <p>Below is some python code that illustrates my problem : the fourth dot takes a very long time to appear (if not, increase the size of the array)</p> <pre><code>from pylab import * threshold = 7 print '.' d = 10*rand(10000000) print '.' b = d&lt;threshold print '.' durations=[] for i in xrange(len(b)): if b[i] and (i==0 or not b[i-1]): counter=1 if i&gt;0 and b[i-1] and b[i]: counter+=1 if (b[i-1] and not b[i]) or i==len(b)-1: durations.append(counter) print '.' </code></pre>
19
2009-07-01T00:19:18Z
32,681,075
<p>Fully numpy vectorized and generic RLE for any array (works with strings, booleans etc too).</p> <p>Outputs tuple of run lengths, start positions, and values.</p> <pre><code>import numpy as np def rle(inarray): """ run length encoding. Partial credit to R rle function. Multi datatype arrays catered for including non Numpy returns: tuple (runlengths, startpositions, values) """ ia = np.array(inarray) # force numpy n = len(ia) if n == 0: return (None, None, None) else: y = np.array(ia[1:] != ia[:-1]) # pairwise unequal (string safe) i = np.append(np.where(y), n - 1) # must include last element posi z = np.diff(np.append(-1, i)) # run lengths p = np.cumsum(np.append(0, z))[:-1] # positions return(z, p, ia[i]) </code></pre> <p>Pretty fast (i7):</p> <pre><code>xx = np.random.randint(0, 5, 1000000) %timeit yy = rle(xx) 100 loops, best of 3: 18.6 ms per loop </code></pre> <p>Multiple data types:</p> <pre><code>rle([True, True, True, False, True, False, False]) Out[8]: (array([3, 1, 1, 2]), array([0, 3, 4, 5]), array([ True, False, True, False], dtype=bool)) rle(np.array([5, 4, 4, 4, 4, 0, 0])) Out[9]: (array([1, 4, 2]), array([0, 1, 5]), array([5, 4, 0])) rle(["hello", "hello", "my", "friend", "okay", "okay", "bye"]) Out[10]: (array([2, 1, 1, 2, 1]), array([0, 2, 3, 4, 6]), array(['hello', 'my', 'friend', 'okay', 'bye'], dtype='|S6')) </code></pre> <p>Same results as Alex Martelli above:</p> <pre><code>xx = np.random.randint(0, 2, 20) xx Out[60]: array([1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1]) am = runs_of_ones_array(xx) tb = rle(xx) am Out[63]: array([4, 5, 2, 5]) tb[0][tb[2] == 1] Out[64]: array([4, 5, 2, 5]) %timeit runs_of_ones_array(xx) 10000 loops, best of 3: 28.5 µs per loop %timeit rle(xx) 10000 loops, best of 3: 38.2 µs per loop </code></pre> <p>Slightly slower than Alex (but still very fast), and much more flexible.</p>
5
2015-09-20T15:30:43Z
[ "python", "matlab", "numpy", "matplotlib" ]
Object Attribute in Random List Not Accessible in Python
1,066,827
<p>I'm working on my first object oriented bit of python and I have the following:</p> <pre><code>#!/usr/bin/python import random class triangle: # Angle A To Angle C Connects Side F # Angle C to Angle B Connects Side D # Angle B to Angle A Connects Side E def __init__(self, a, b, c, d, e, f): self.a = a self.b = b self.c = c self.d = d self.e = e self.f = f #def solver: #pass #initialize Triangle myTri = triangle(0,0,0,0,0,0) #Pick Three Random Angles or Sides to Generate Values For sample = random.sample([myTri.a, myTri.b, myTri.c, myTri.d, myTri.e, myTri.f], 3) #Sets the three randomly picked variables to a Random Number sample[0] = random.randint(1, 100) sample[1] = random.randint(1, 100) sample[2] = random.randint(1, 100) </code></pre> <p>How do I pass myTri.a, for example to random.randint. It is passing the value of '0' which it initialized. I want to be able to assign a random value to three of the .a-.f attributes of myTri. What am I missing?</p>
1
2009-07-01T00:57:37Z
1,066,871
<p>To assign to <code>a</code>, <code>b</code>, and <code>c</code>:</p> <pre><code>myTri.a = random.randint(1, 100) myTri.b = random.randint(1, 100) myTri.c = random.randint(1, 100) </code></pre> <p>To assign to one random attribute from <code>a</code>-<code>f</code>:</p> <pre><code>attrs = ['a', 'b', 'c', 'd', 'e', 'f'] setattr(myTri, random.choice(attrs), random.randint(1, 100)) </code></pre> <p>To assign to three random attributes from <code>a</code>-<code>f</code>:</p> <pre><code>attrs = ['a', 'b', 'c', 'd', 'e', 'f'] for attr in random.sample(attrs, 3): setattr(myTri, attr, random.randint(1, 100)) </code></pre>
2
2009-07-01T01:17:32Z
[ "python", "random", "object", "oop" ]
Object Attribute in Random List Not Accessible in Python
1,066,827
<p>I'm working on my first object oriented bit of python and I have the following:</p> <pre><code>#!/usr/bin/python import random class triangle: # Angle A To Angle C Connects Side F # Angle C to Angle B Connects Side D # Angle B to Angle A Connects Side E def __init__(self, a, b, c, d, e, f): self.a = a self.b = b self.c = c self.d = d self.e = e self.f = f #def solver: #pass #initialize Triangle myTri = triangle(0,0,0,0,0,0) #Pick Three Random Angles or Sides to Generate Values For sample = random.sample([myTri.a, myTri.b, myTri.c, myTri.d, myTri.e, myTri.f], 3) #Sets the three randomly picked variables to a Random Number sample[0] = random.randint(1, 100) sample[1] = random.randint(1, 100) sample[2] = random.randint(1, 100) </code></pre> <p>How do I pass myTri.a, for example to random.randint. It is passing the value of '0' which it initialized. I want to be able to assign a random value to three of the .a-.f attributes of myTri. What am I missing?</p>
1
2009-07-01T00:57:37Z
1,066,873
<p>When you say <code>[myTri.a, myTri.b, ...]</code> you are not getting a list of the variables themselves, or references to them. Instead you are getting just their values. Since you know they were initialized to <code>0</code>, it is as if you had written <code>[0, 0, 0, 0, 0, 0]</code>. There's no difference.</p> <p>Then later when you try to assign to <code>sample[0]</code>, you are actually just overwriting the 0 that is stored in that array with a random value. Python knows nothing at all about <code>myTri</code> at that point; the connection is lost.</p> <p>Here's what you can do to get the effect you're aiming for. First, pass a list of variable names we want to assign to later to <code>random.sample</code>:</p> <pre><code>sample = random.sample(["a", "b", "c", "d", "e", "f"], 3) </code></pre> <p>That'll give us back 3 random variable names. Now we want to assign to the variables with those same names. We can do that by using the special <code>setattr</code> function, which takes an object and a variable name and sets its value. For instance, <code>setattr(myTri, "b", 72)</code> does the same thing as <code>myTri.b = 72</code>. So rewritten we have:</p> <pre><code>setattr(myTri, sample[0], random.randint(1, 100)) setattr(myTri, sample[1], random.randint(1, 100)) setattr(myTri, sample[2], random.randint(1, 100)) </code></pre> <p>The major concept here is that you're doing a bit of reflection, also known as introspection. You've got dynamic variable names--you don't know exactly who you're messing with--so you've got to consult with some more exotic, out of the way language constructs. Normally I'd actually caution against such tomfoolery, but this is a rare instance where introspection is a reasonable solution.</p>
5
2009-07-01T01:18:40Z
[ "python", "random", "object", "oop" ]
Object Attribute in Random List Not Accessible in Python
1,066,827
<p>I'm working on my first object oriented bit of python and I have the following:</p> <pre><code>#!/usr/bin/python import random class triangle: # Angle A To Angle C Connects Side F # Angle C to Angle B Connects Side D # Angle B to Angle A Connects Side E def __init__(self, a, b, c, d, e, f): self.a = a self.b = b self.c = c self.d = d self.e = e self.f = f #def solver: #pass #initialize Triangle myTri = triangle(0,0,0,0,0,0) #Pick Three Random Angles or Sides to Generate Values For sample = random.sample([myTri.a, myTri.b, myTri.c, myTri.d, myTri.e, myTri.f], 3) #Sets the three randomly picked variables to a Random Number sample[0] = random.randint(1, 100) sample[1] = random.randint(1, 100) sample[2] = random.randint(1, 100) </code></pre> <p>How do I pass myTri.a, for example to random.randint. It is passing the value of '0' which it initialized. I want to be able to assign a random value to three of the .a-.f attributes of myTri. What am I missing?</p>
1
2009-07-01T00:57:37Z
1,066,982
<p>Alternative to using setattr: do it when you create a Triangle instance.</p> <pre><code>args = [random.randint(1, 100) for i in xrange(3)] + [0, 0, 0] random.shuffle(args) my_tri = Triangle(*args) </code></pre>
0
2009-07-01T02:06:44Z
[ "python", "random", "object", "oop" ]
How to extract top-level domain name (TLD) from URL
1,066,933
<p>how would you extract the domain name from a URL, excluding any subdomains?</p> <p>My initial simplistic attempt was:</p> <pre><code>'.'.join(urlparse.urlparse(url).netloc.split('.')[-2:]) </code></pre> <p>This works for <a href="http://www.foo.com">http://www.foo.com</a>, but not <a href="http://www.foo.com.au">http://www.foo.com.au</a>. Is there a way to do this properly without using special knowledge about valid TLDs (Top Level Domains) or country codes (because they change).</p> <p>thanks</p>
31
2009-07-01T01:42:03Z
1,066,947
<p>No, there is no "intrinsic" way of knowing that (e.g.) <code>zap.co.it</code> is a subdomain (because Italy's registrar DOES sell domains such as <code>co.it</code>) while <code>zap.co.uk</code> <em>isn't</em> (because the UK's registrar DOESN'T sell domains such as <code>co.uk</code>, but only like <code>zap.co.uk</code>).</p> <p>You'll just have to use an auxiliary table (or online source) to tell you which TLD's behave peculiarly like UK's and Australia's -- there's no way of divining that from just staring at the string without such extra semantic knowledge (of course it can change eventually, but if you can find a good online source that source will also change accordingly, one hopes!-).</p>
35
2009-07-01T01:48:50Z
[ "python", "url", "parsing", "dns", "extract" ]
How to extract top-level domain name (TLD) from URL
1,066,933
<p>how would you extract the domain name from a URL, excluding any subdomains?</p> <p>My initial simplistic attempt was:</p> <pre><code>'.'.join(urlparse.urlparse(url).netloc.split('.')[-2:]) </code></pre> <p>This works for <a href="http://www.foo.com">http://www.foo.com</a>, but not <a href="http://www.foo.com.au">http://www.foo.com.au</a>. Is there a way to do this properly without using special knowledge about valid TLDs (Top Level Domains) or country codes (because they change).</p> <p>thanks</p>
31
2009-07-01T01:42:03Z
1,066,955
<p>There are many, many TLD's. Here's the list:</p> <p><a href="http://data.iana.org/TLD/tlds-alpha-by-domain.txt" rel="nofollow">http://data.iana.org/TLD/tlds-alpha-by-domain.txt</a></p> <p>Here's another list</p> <p><a href="http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains" rel="nofollow">http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains</a></p> <p>Here's another list</p> <p><a href="http://www.iana.org/domains/root/db/" rel="nofollow">http://www.iana.org/domains/root/db/</a></p>
2
2009-07-01T01:51:45Z
[ "python", "url", "parsing", "dns", "extract" ]
How to extract top-level domain name (TLD) from URL
1,066,933
<p>how would you extract the domain name from a URL, excluding any subdomains?</p> <p>My initial simplistic attempt was:</p> <pre><code>'.'.join(urlparse.urlparse(url).netloc.split('.')[-2:]) </code></pre> <p>This works for <a href="http://www.foo.com">http://www.foo.com</a>, but not <a href="http://www.foo.com.au">http://www.foo.com.au</a>. Is there a way to do this properly without using special knowledge about valid TLDs (Top Level Domains) or country codes (because they change).</p> <p>thanks</p>
31
2009-07-01T01:42:03Z
1,069,780
<p>using <a href="http://mxr.mozilla.org/mozilla/source/netwerk/dns/src/effective_tld_names.dat?raw=1">this file of effective tlds</a> which <a href="http://stackoverflow.com/questions/569137/how-to-get-domain-name-from-url/569176#569176">someone else</a> found on mozzila's website:</p> <pre><code>from __future__ import with_statement from urlparse import urlparse # load tlds, ignore comments and empty lines: with open("effective_tld_names.dat.txt") as tld_file: tlds = [line.strip() for line in tld_file if line[0] not in "/\n"] def get_domain(url, tlds): url_elements = urlparse(url)[1].split('.') # url_elements = ["abcde","co","uk"] for i in range(-len(url_elements), 0): last_i_elements = url_elements[i:] # i=-3: ["abcde","co","uk"] # i=-2: ["co","uk"] # i=-1: ["uk"] etc candidate = ".".join(last_i_elements) # abcde.co.uk, co.uk, uk wildcard_candidate = ".".join(["*"] + last_i_elements[1:]) # *.co.uk, *.uk, * exception_candidate = "!" + candidate # match tlds: if (exception_candidate in tlds): return ".".join(url_elements[i:]) if (candidate in tlds or wildcard_candidate in tlds): return ".".join(url_elements[i-1:]) # returns "abcde.co.uk" raise ValueError("Domain not in global list of TLDs") print get_domain("http://abcde.co.uk", tlds) </code></pre> <p>results in:</p> <pre><code>abcde.co.uk </code></pre> <p>I'd appreciate it if someone let me know which bits of the above could be rewritten in a more pythonic way. For example, there must be a better way of iterating over the <code>last_i_elements</code> list, but I couldn't think of one. I also don't know if <code>ValueError</code> is the best thing to raise. Comments?</p>
37
2009-07-01T15:23:52Z
[ "python", "url", "parsing", "dns", "extract" ]
How to extract top-level domain name (TLD) from URL
1,066,933
<p>how would you extract the domain name from a URL, excluding any subdomains?</p> <p>My initial simplistic attempt was:</p> <pre><code>'.'.join(urlparse.urlparse(url).netloc.split('.')[-2:]) </code></pre> <p>This works for <a href="http://www.foo.com">http://www.foo.com</a>, but not <a href="http://www.foo.com.au">http://www.foo.com.au</a>. Is there a way to do this properly without using special knowledge about valid TLDs (Top Level Domains) or country codes (because they change).</p> <p>thanks</p>
31
2009-07-01T01:42:03Z
7,388,904
<p>Here's a great python module someone wrote to solve this problem after seeing this question: <a href="https://github.com/john-kurkowski/tldextract">https://github.com/john-kurkowski/tldextract</a></p> <p>The module looks up TLDs in the <a href="https://www.publicsuffix.org/">Public Suffix List</a>, mantained by Mozilla volunteers</p> <p>Quote:</p> <blockquote> <p><code>tldextract</code> on the other hand knows what all gTLDs [<em>Generic Top-Level Domains</em>] and ccTLDs [<em>Country Code Top-Level Domains</em>] look like by looking up the currently living ones according to the <a href="https://www.publicsuffix.org/">Public Suffix List</a>. So, given a URL, it knows its subdomain from its domain, and its domain from its country code.</p> </blockquote>
33
2011-09-12T13:46:06Z
[ "python", "url", "parsing", "dns", "extract" ]
How to extract top-level domain name (TLD) from URL
1,066,933
<p>how would you extract the domain name from a URL, excluding any subdomains?</p> <p>My initial simplistic attempt was:</p> <pre><code>'.'.join(urlparse.urlparse(url).netloc.split('.')[-2:]) </code></pre> <p>This works for <a href="http://www.foo.com">http://www.foo.com</a>, but not <a href="http://www.foo.com.au">http://www.foo.com.au</a>. Is there a way to do this properly without using special knowledge about valid TLDs (Top Level Domains) or country codes (because they change).</p> <p>thanks</p>
31
2009-07-01T01:42:03Z
15,508,109
<p>Here's how I handle it:</p> <pre><code>if not url.startswith('http'): url = 'http://'+url website = urlparse.urlparse(url)[1] domain = ('.').join(website.split('.')[-2:]) match = re.search(r'((www\.)?([A-Z0-9.-]+\.[A-Z]{2,4}))', domain, re.I) if not match: sys.exit(2) elif not match.group(0): sys.exit(2) </code></pre>
0
2013-03-19T18:53:47Z
[ "python", "url", "parsing", "dns", "extract" ]
How to extract top-level domain name (TLD) from URL
1,066,933
<p>how would you extract the domain name from a URL, excluding any subdomains?</p> <p>My initial simplistic attempt was:</p> <pre><code>'.'.join(urlparse.urlparse(url).netloc.split('.')[-2:]) </code></pre> <p>This works for <a href="http://www.foo.com">http://www.foo.com</a>, but not <a href="http://www.foo.com.au">http://www.foo.com.au</a>. Is there a way to do this properly without using special knowledge about valid TLDs (Top Level Domains) or country codes (because they change).</p> <p>thanks</p>
31
2009-07-01T01:42:03Z
16,580,707
<p>Using python tld</p> <p><a href="https://pypi.python.org/pypi/tld">https://pypi.python.org/pypi/tld</a></p> <p>pip install tld</p> <pre><code>from tld import get_tld print get_tld("http://www.google.co.uk") </code></pre> <h1>print out: google.co.uk</h1>
16
2013-05-16T06:46:41Z
[ "python", "url", "parsing", "dns", "extract" ]
How to extract top-level domain name (TLD) from URL
1,066,933
<p>how would you extract the domain name from a URL, excluding any subdomains?</p> <p>My initial simplistic attempt was:</p> <pre><code>'.'.join(urlparse.urlparse(url).netloc.split('.')[-2:]) </code></pre> <p>This works for <a href="http://www.foo.com">http://www.foo.com</a>, but not <a href="http://www.foo.com.au">http://www.foo.com.au</a>. Is there a way to do this properly without using special knowledge about valid TLDs (Top Level Domains) or country codes (because they change).</p> <p>thanks</p>
31
2009-07-01T01:42:03Z
29,525,805
<p>Until get_tld is updated for all the new ones, I pull the tld from the error. Sure it's bad code but it works.</p> <pre><code>def get_tld(): try: return get_tld(self.content_url) except Exception, e: re_domain = re.compile("Domain ([^ ]+) didn't match any existing TLD name!"); matchObj = re_domain.findall(str(e)) if matchObj: for m in matchObj: return m raise e </code></pre>
0
2015-04-08T21:36:29Z
[ "python", "url", "parsing", "dns", "extract" ]
Translating Perl to Python
1,067,060
<p>I found this Perl script while <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/25860">migrating my SQLite database to mysql</a></p> <p>I was wondering (since I don't know Perl) how could one rewrite this in Python?</p> <p>Bonus points for the shortest (code) answer :)</p> <p><strong>edit</strong>: sorry I meant shortest code, not strictly shortest answer</p> <pre><code>#! /usr/bin/perl while ($line = &lt;&gt;){ if (($line !~ /BEGIN TRANSACTION/) &amp;&amp; ($line !~ /COMMIT/) &amp;&amp; ($line !~ /sqlite_sequence/) &amp;&amp; ($line !~ /CREATE UNIQUE INDEX/)){ if ($line =~ /CREATE TABLE \"([a-z_]*)\"(.*)/){ $name = $1; $sub = $2; $sub =~ s/\"//g; #" $line = "DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n"; } elsif ($line =~ /INSERT INTO \"([a-z_]*)\"(.*)/){ $line = "INSERT INTO $1$2\n"; $line =~ s/\"/\\\"/g; #" $line =~ s/\"/\'/g; #" }else{ $line =~ s/\'\'/\\\'/g; #' } $line =~ s/([^\\'])\'t\'(.)/$1THIS_IS_TRUE$2/g; #' $line =~ s/THIS_IS_TRUE/1/g; $line =~ s/([^\\'])\'f\'(.)/$1THIS_IS_FALSE$2/g; #' $line =~ s/THIS_IS_FALSE/0/g; $line =~ s/AUTOINCREMENT/AUTO_INCREMENT/g; print $line; } } </code></pre> <p>Some additional code was necessary to successfully migrate the sqlite database (handles one line Create table statements, foreign keys, fixes a bug in the original program that converted empty fields <code>''</code> to <code>\'</code>. </p> <p>I <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/1067365#1067365">posted the code on the migrating my SQLite database to mysql Question</a></p>
14
2009-07-01T02:50:40Z
1,067,145
<p>Based on <a href="http://docs.python.org/dev/howto/regex.html" rel="nofollow">http://docs.python.org/dev/howto/regex.html</a> ...</p> <ol> <li>Replace <code>$line =~ /.*/</code> with <code>re.search(r".*", line)</code>.</li> <li><code>$line !~ /.*/</code> is just <code>!($line =~ /.*/)</code>.</li> <li>Replace <code>$line =~ s/.*/x/g</code> with <code>line=re.sub(r".*", "x", line)</code>.</li> <li>Replace <code>$1</code> through <code>$9</code> inside <code>re.sub</code> with <code>\1</code> through <code>\9</code> respectively.</li> <li>Outside a sub, save the return value, i.e. <code>m=re.search()</code>, and replace <code>$1</code> with the return value of <code>m.group(1)</code>.</li> <li>For <code>"INSERT INTO $1$2\n"</code> specifically, you can do <code>"INSERT INTO %s%s\n" % (m.group(1), m.group(2))</code>.</li> </ol>
3
2009-07-01T03:22:55Z
[ "python", "perl", "rewrite" ]
Translating Perl to Python
1,067,060
<p>I found this Perl script while <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/25860">migrating my SQLite database to mysql</a></p> <p>I was wondering (since I don't know Perl) how could one rewrite this in Python?</p> <p>Bonus points for the shortest (code) answer :)</p> <p><strong>edit</strong>: sorry I meant shortest code, not strictly shortest answer</p> <pre><code>#! /usr/bin/perl while ($line = &lt;&gt;){ if (($line !~ /BEGIN TRANSACTION/) &amp;&amp; ($line !~ /COMMIT/) &amp;&amp; ($line !~ /sqlite_sequence/) &amp;&amp; ($line !~ /CREATE UNIQUE INDEX/)){ if ($line =~ /CREATE TABLE \"([a-z_]*)\"(.*)/){ $name = $1; $sub = $2; $sub =~ s/\"//g; #" $line = "DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n"; } elsif ($line =~ /INSERT INTO \"([a-z_]*)\"(.*)/){ $line = "INSERT INTO $1$2\n"; $line =~ s/\"/\\\"/g; #" $line =~ s/\"/\'/g; #" }else{ $line =~ s/\'\'/\\\'/g; #' } $line =~ s/([^\\'])\'t\'(.)/$1THIS_IS_TRUE$2/g; #' $line =~ s/THIS_IS_TRUE/1/g; $line =~ s/([^\\'])\'f\'(.)/$1THIS_IS_FALSE$2/g; #' $line =~ s/THIS_IS_FALSE/0/g; $line =~ s/AUTOINCREMENT/AUTO_INCREMENT/g; print $line; } } </code></pre> <p>Some additional code was necessary to successfully migrate the sqlite database (handles one line Create table statements, foreign keys, fixes a bug in the original program that converted empty fields <code>''</code> to <code>\'</code>. </p> <p>I <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/1067365#1067365">posted the code on the migrating my SQLite database to mysql Question</a></p>
14
2009-07-01T02:50:40Z
1,067,148
<p>I am not sure what is so hard to understand about this that it requires a snide remark as in your comment above. Note that <code>&lt;&gt;</code> is called the diamond operator. <code>s///</code> is the substitution operator and <code>//</code> is the match operator <code>m//</code>.</p>
3
2009-07-01T03:24:32Z
[ "python", "perl", "rewrite" ]
Translating Perl to Python
1,067,060
<p>I found this Perl script while <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/25860">migrating my SQLite database to mysql</a></p> <p>I was wondering (since I don't know Perl) how could one rewrite this in Python?</p> <p>Bonus points for the shortest (code) answer :)</p> <p><strong>edit</strong>: sorry I meant shortest code, not strictly shortest answer</p> <pre><code>#! /usr/bin/perl while ($line = &lt;&gt;){ if (($line !~ /BEGIN TRANSACTION/) &amp;&amp; ($line !~ /COMMIT/) &amp;&amp; ($line !~ /sqlite_sequence/) &amp;&amp; ($line !~ /CREATE UNIQUE INDEX/)){ if ($line =~ /CREATE TABLE \"([a-z_]*)\"(.*)/){ $name = $1; $sub = $2; $sub =~ s/\"//g; #" $line = "DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n"; } elsif ($line =~ /INSERT INTO \"([a-z_]*)\"(.*)/){ $line = "INSERT INTO $1$2\n"; $line =~ s/\"/\\\"/g; #" $line =~ s/\"/\'/g; #" }else{ $line =~ s/\'\'/\\\'/g; #' } $line =~ s/([^\\'])\'t\'(.)/$1THIS_IS_TRUE$2/g; #' $line =~ s/THIS_IS_TRUE/1/g; $line =~ s/([^\\'])\'f\'(.)/$1THIS_IS_FALSE$2/g; #' $line =~ s/THIS_IS_FALSE/0/g; $line =~ s/AUTOINCREMENT/AUTO_INCREMENT/g; print $line; } } </code></pre> <p>Some additional code was necessary to successfully migrate the sqlite database (handles one line Create table statements, foreign keys, fixes a bug in the original program that converted empty fields <code>''</code> to <code>\'</code>. </p> <p>I <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/1067365#1067365">posted the code on the migrating my SQLite database to mysql Question</a></p>
14
2009-07-01T02:50:40Z
1,067,151
<p>Here's a pretty literal translation with just the minimum of obvious style changes (putting all code into a function, using string rather than re operations where possible).</p> <pre><code>import re, fileinput def main(): for line in fileinput.input(): process = False for nope in ('BEGIN TRANSACTION','COMMIT', 'sqlite_sequence','CREATE UNIQUE INDEX'): if nope in line: break else: process = True if not process: continue m = re.search('CREATE TABLE "([a-z_]*)"(.*)', line) if m: name, sub = m.groups() line = '''DROP TABLE IF EXISTS %(name)s; CREATE TABLE IF NOT EXISTS %(name)s%(sub)s ''' line = line % dict(name=name, sub=sub) else: m = re.search('INSERT INTO "([a-z_]*)"(.*)', line) if m: line = 'INSERT INTO %s%s\n' % m.groups() line = line.replace('"', r'\"') line = line.replace('"', "'") line = re.sub(r"([^'])'t'(.)", r"\1THIS_IS_TRUE\2", line) line = line.replace('THIS_IS_TRUE', '1') line = re.sub(r"([^'])'f'(.)", r"\1THIS_IS_FALSE\2", line) line = line.replace('THIS_IS_FALSE', '0') line = line.replace('AUTOINCREMENT', 'AUTO_INCREMENT') print line, main() </code></pre>
45
2009-07-01T03:25:54Z
[ "python", "perl", "rewrite" ]
Translating Perl to Python
1,067,060
<p>I found this Perl script while <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/25860">migrating my SQLite database to mysql</a></p> <p>I was wondering (since I don't know Perl) how could one rewrite this in Python?</p> <p>Bonus points for the shortest (code) answer :)</p> <p><strong>edit</strong>: sorry I meant shortest code, not strictly shortest answer</p> <pre><code>#! /usr/bin/perl while ($line = &lt;&gt;){ if (($line !~ /BEGIN TRANSACTION/) &amp;&amp; ($line !~ /COMMIT/) &amp;&amp; ($line !~ /sqlite_sequence/) &amp;&amp; ($line !~ /CREATE UNIQUE INDEX/)){ if ($line =~ /CREATE TABLE \"([a-z_]*)\"(.*)/){ $name = $1; $sub = $2; $sub =~ s/\"//g; #" $line = "DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n"; } elsif ($line =~ /INSERT INTO \"([a-z_]*)\"(.*)/){ $line = "INSERT INTO $1$2\n"; $line =~ s/\"/\\\"/g; #" $line =~ s/\"/\'/g; #" }else{ $line =~ s/\'\'/\\\'/g; #' } $line =~ s/([^\\'])\'t\'(.)/$1THIS_IS_TRUE$2/g; #' $line =~ s/THIS_IS_TRUE/1/g; $line =~ s/([^\\'])\'f\'(.)/$1THIS_IS_FALSE$2/g; #' $line =~ s/THIS_IS_FALSE/0/g; $line =~ s/AUTOINCREMENT/AUTO_INCREMENT/g; print $line; } } </code></pre> <p>Some additional code was necessary to successfully migrate the sqlite database (handles one line Create table statements, foreign keys, fixes a bug in the original program that converted empty fields <code>''</code> to <code>\'</code>. </p> <p>I <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/1067365#1067365">posted the code on the migrating my SQLite database to mysql Question</a></p>
14
2009-07-01T02:50:40Z
1,067,152
<p>Shortest? The tilde signifies a regex in perl. "import re" and go from there. The only key differences are that you'll be using \1 and \2 instead of $1 and $2 when you assign values, and you'll be using %s for when you're replacing regexp matches inside strings.</p>
1
2009-07-01T03:26:16Z
[ "python", "perl", "rewrite" ]
Translating Perl to Python
1,067,060
<p>I found this Perl script while <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/25860">migrating my SQLite database to mysql</a></p> <p>I was wondering (since I don't know Perl) how could one rewrite this in Python?</p> <p>Bonus points for the shortest (code) answer :)</p> <p><strong>edit</strong>: sorry I meant shortest code, not strictly shortest answer</p> <pre><code>#! /usr/bin/perl while ($line = &lt;&gt;){ if (($line !~ /BEGIN TRANSACTION/) &amp;&amp; ($line !~ /COMMIT/) &amp;&amp; ($line !~ /sqlite_sequence/) &amp;&amp; ($line !~ /CREATE UNIQUE INDEX/)){ if ($line =~ /CREATE TABLE \"([a-z_]*)\"(.*)/){ $name = $1; $sub = $2; $sub =~ s/\"//g; #" $line = "DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n"; } elsif ($line =~ /INSERT INTO \"([a-z_]*)\"(.*)/){ $line = "INSERT INTO $1$2\n"; $line =~ s/\"/\\\"/g; #" $line =~ s/\"/\'/g; #" }else{ $line =~ s/\'\'/\\\'/g; #' } $line =~ s/([^\\'])\'t\'(.)/$1THIS_IS_TRUE$2/g; #' $line =~ s/THIS_IS_TRUE/1/g; $line =~ s/([^\\'])\'f\'(.)/$1THIS_IS_FALSE$2/g; #' $line =~ s/THIS_IS_FALSE/0/g; $line =~ s/AUTOINCREMENT/AUTO_INCREMENT/g; print $line; } } </code></pre> <p>Some additional code was necessary to successfully migrate the sqlite database (handles one line Create table statements, foreign keys, fixes a bug in the original program that converted empty fields <code>''</code> to <code>\'</code>. </p> <p>I <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/1067365#1067365">posted the code on the migrating my SQLite database to mysql Question</a></p>
14
2009-07-01T02:50:40Z
1,068,921
<p>Real issue is do you know actually how to migrate the database? What is presented is merely a search and replace loop.</p>
1
2009-07-01T12:33:18Z
[ "python", "perl", "rewrite" ]
Translating Perl to Python
1,067,060
<p>I found this Perl script while <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/25860">migrating my SQLite database to mysql</a></p> <p>I was wondering (since I don't know Perl) how could one rewrite this in Python?</p> <p>Bonus points for the shortest (code) answer :)</p> <p><strong>edit</strong>: sorry I meant shortest code, not strictly shortest answer</p> <pre><code>#! /usr/bin/perl while ($line = &lt;&gt;){ if (($line !~ /BEGIN TRANSACTION/) &amp;&amp; ($line !~ /COMMIT/) &amp;&amp; ($line !~ /sqlite_sequence/) &amp;&amp; ($line !~ /CREATE UNIQUE INDEX/)){ if ($line =~ /CREATE TABLE \"([a-z_]*)\"(.*)/){ $name = $1; $sub = $2; $sub =~ s/\"//g; #" $line = "DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n"; } elsif ($line =~ /INSERT INTO \"([a-z_]*)\"(.*)/){ $line = "INSERT INTO $1$2\n"; $line =~ s/\"/\\\"/g; #" $line =~ s/\"/\'/g; #" }else{ $line =~ s/\'\'/\\\'/g; #' } $line =~ s/([^\\'])\'t\'(.)/$1THIS_IS_TRUE$2/g; #' $line =~ s/THIS_IS_TRUE/1/g; $line =~ s/([^\\'])\'f\'(.)/$1THIS_IS_FALSE$2/g; #' $line =~ s/THIS_IS_FALSE/0/g; $line =~ s/AUTOINCREMENT/AUTO_INCREMENT/g; print $line; } } </code></pre> <p>Some additional code was necessary to successfully migrate the sqlite database (handles one line Create table statements, foreign keys, fixes a bug in the original program that converted empty fields <code>''</code> to <code>\'</code>. </p> <p>I <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/1067365#1067365">posted the code on the migrating my SQLite database to mysql Question</a></p>
14
2009-07-01T02:50:40Z
1,070,463
<p>Here is a slightly better version of the original.</p> <pre><code>#! /usr/bin/perl use strict; use warnings; use 5.010; # for s/\K//; while( &lt;&gt; ){ next if m' BEGIN TRANSACTION | COMMIT | sqlite_sequence | CREATE UNIQUE INDEX 'x; if( my($name,$sub) = m'CREATE TABLE \"([a-z_]*)\"(.*)' ){ # remove " $sub =~ s/\"//g; #" $_ = "DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n"; }elsif( /INSERT INTO \"([a-z_]*)\"(.*)/ ){ $_ = "INSERT INTO $1$2\n"; # " =&gt; \" s/\"/\\\"/g; #" # " =&gt; ' s/\"/\'/g; #" }else{ # '' =&gt; \' s/\'\'/\\\'/g; #' } # 't' =&gt; 1 s/[^\\']\K\'t\'/1/g; #' # 'f' =&gt; 0 s/[^\\']\K\'f\'/0/g; #' s/AUTOINCREMENT/AUTO_INCREMENT/g; print; } </code></pre>
5
2009-07-01T17:48:28Z
[ "python", "perl", "rewrite" ]
Translating Perl to Python
1,067,060
<p>I found this Perl script while <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/25860">migrating my SQLite database to mysql</a></p> <p>I was wondering (since I don't know Perl) how could one rewrite this in Python?</p> <p>Bonus points for the shortest (code) answer :)</p> <p><strong>edit</strong>: sorry I meant shortest code, not strictly shortest answer</p> <pre><code>#! /usr/bin/perl while ($line = &lt;&gt;){ if (($line !~ /BEGIN TRANSACTION/) &amp;&amp; ($line !~ /COMMIT/) &amp;&amp; ($line !~ /sqlite_sequence/) &amp;&amp; ($line !~ /CREATE UNIQUE INDEX/)){ if ($line =~ /CREATE TABLE \"([a-z_]*)\"(.*)/){ $name = $1; $sub = $2; $sub =~ s/\"//g; #" $line = "DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n"; } elsif ($line =~ /INSERT INTO \"([a-z_]*)\"(.*)/){ $line = "INSERT INTO $1$2\n"; $line =~ s/\"/\\\"/g; #" $line =~ s/\"/\'/g; #" }else{ $line =~ s/\'\'/\\\'/g; #' } $line =~ s/([^\\'])\'t\'(.)/$1THIS_IS_TRUE$2/g; #' $line =~ s/THIS_IS_TRUE/1/g; $line =~ s/([^\\'])\'f\'(.)/$1THIS_IS_FALSE$2/g; #' $line =~ s/THIS_IS_FALSE/0/g; $line =~ s/AUTOINCREMENT/AUTO_INCREMENT/g; print $line; } } </code></pre> <p>Some additional code was necessary to successfully migrate the sqlite database (handles one line Create table statements, foreign keys, fixes a bug in the original program that converted empty fields <code>''</code> to <code>\'</code>. </p> <p>I <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/1067365#1067365">posted the code on the migrating my SQLite database to mysql Question</a></p>
14
2009-07-01T02:50:40Z
3,675,869
<p><a href="http://stackoverflow.com/questions/1067060/translating-perl-to-python/1067151#1067151">Alex Martelli's solution above</a> works good, but needs some fixes and additions:</p> <p>In the lines using regular expression substitution, the insertion of the matched groups must be double-escaped OR the replacement string must be prefixed with r to mark is as regular expression:</p> <pre><code>line = re.sub(r"([^'])'t'(.)", "\\1THIS_IS_TRUE\\2", line) </code></pre> <p>or</p> <pre><code>line = re.sub(r"([^'])'f'(.)", r"\1THIS_IS_FALSE\2", line) </code></pre> <p>Also, this line should be added before print:</p> <pre><code>line = line.replace('AUTOINCREMENT', 'AUTO_INCREMENT') </code></pre> <p>Last, the column names in create statements should be backticks in MySQL. Add this in line 15:</p> <pre><code> sub = sub.replace('"','`') </code></pre> <p>Here's the complete script with modifications:</p> <pre><code>import re, fileinput def main(): for line in fileinput.input(): process = False for nope in ('BEGIN TRANSACTION','COMMIT', 'sqlite_sequence','CREATE UNIQUE INDEX'): if nope in line: break else: process = True if not process: continue m = re.search('CREATE TABLE "([a-z_]*)"(.*)', line) if m: name, sub = m.groups() sub = sub.replace('"','`') line = '''DROP TABLE IF EXISTS %(name)s; CREATE TABLE IF NOT EXISTS %(name)s%(sub)s ''' line = line % dict(name=name, sub=sub) else: m = re.search('INSERT INTO "([a-z_]*)"(.*)', line) if m: line = 'INSERT INTO %s%s\n' % m.groups() line = line.replace('"', r'\"') line = line.replace('"', "'") line = re.sub(r"([^'])'t'(.)", "\\1THIS_IS_TRUE\\2", line) line = line.replace('THIS_IS_TRUE', '1') line = re.sub(r"([^'])'f'(.)", "\\1THIS_IS_FALSE\\2", line) line = line.replace('THIS_IS_FALSE', '0') line = line.replace('AUTOINCREMENT', 'AUTO_INCREMENT') if re.search('^CREATE INDEX', line): line = line.replace('"','`') print line, main() </code></pre>
10
2010-09-09T10:55:41Z
[ "python", "perl", "rewrite" ]
Translating Perl to Python
1,067,060
<p>I found this Perl script while <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/25860">migrating my SQLite database to mysql</a></p> <p>I was wondering (since I don't know Perl) how could one rewrite this in Python?</p> <p>Bonus points for the shortest (code) answer :)</p> <p><strong>edit</strong>: sorry I meant shortest code, not strictly shortest answer</p> <pre><code>#! /usr/bin/perl while ($line = &lt;&gt;){ if (($line !~ /BEGIN TRANSACTION/) &amp;&amp; ($line !~ /COMMIT/) &amp;&amp; ($line !~ /sqlite_sequence/) &amp;&amp; ($line !~ /CREATE UNIQUE INDEX/)){ if ($line =~ /CREATE TABLE \"([a-z_]*)\"(.*)/){ $name = $1; $sub = $2; $sub =~ s/\"//g; #" $line = "DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n"; } elsif ($line =~ /INSERT INTO \"([a-z_]*)\"(.*)/){ $line = "INSERT INTO $1$2\n"; $line =~ s/\"/\\\"/g; #" $line =~ s/\"/\'/g; #" }else{ $line =~ s/\'\'/\\\'/g; #' } $line =~ s/([^\\'])\'t\'(.)/$1THIS_IS_TRUE$2/g; #' $line =~ s/THIS_IS_TRUE/1/g; $line =~ s/([^\\'])\'f\'(.)/$1THIS_IS_FALSE$2/g; #' $line =~ s/THIS_IS_FALSE/0/g; $line =~ s/AUTOINCREMENT/AUTO_INCREMENT/g; print $line; } } </code></pre> <p>Some additional code was necessary to successfully migrate the sqlite database (handles one line Create table statements, foreign keys, fixes a bug in the original program that converted empty fields <code>''</code> to <code>\'</code>. </p> <p>I <a href="http://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql/1067365#1067365">posted the code on the migrating my SQLite database to mysql Question</a></p>
14
2009-07-01T02:50:40Z
6,346,336
<p>all of scripts on this page can't deal with simple sqlite3:</p> <pre><code>PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; CREATE TABLE Filename ( FilenameId INTEGER, Name TEXT DEFAULT '', PRIMARY KEY(FilenameId) ); INSERT INTO "Filename" VALUES(1,''); INSERT INTO "Filename" VALUES(2,'bigfile1'); INSERT INTO "Filename" VALUES(3,'%gconf-tree.xml'); </code></pre> <p>None were able to reformat "table_name" into proper mysql's `table_name` . Some messed up empty string value.</p>
4
2011-06-14T15:48:07Z
[ "python", "perl", "rewrite" ]
Get rid of toplevel tk panewindow while usong tkMessageBox
1,067,900
<p><a href="http://stackoverflow.com/questions/1052420/tkkinter-message-box">link text</a></p> <p>When I do :</p> <pre><code>tkMessageBox.askquestion(title="Symbol Display",message="Is the symbol visible on the console") </code></pre> <p>along with Symbol Display window tk window is also coming. </p> <p>If i press "Yes"...the child window return yes,whereas tk window remains there.</p> <p>Whenever I am tryng to close tk window, End Program - tk comes. on pushing "End Now" button "pythonw.exe" window comes asking to send error report or not.</p> <p>Why is it so ? How can I avoid tk window from popping out without affecting my script execution ???</p>
4
2009-07-01T08:14:21Z
1,067,995
<p>The <em>trick</em> is to invoke withdraw on the Tk root top-level:</p> <pre><code>&gt;&gt;&gt; import tkMessageBox, Tkinter &gt;&gt;&gt; Tkinter.Tk().withdraw() &gt;&gt;&gt; tkMessageBox.askquestion( ... title="Symbol Display", ... message="Is the symbol visible on the console") </code></pre>
5
2009-07-01T08:37:59Z
[ "python", "tkinter" ]
Programmatically detect system-proxy settings on Windows XP with Python
1,068,212
<p>I develop a critical application used by a multi-national company. Users in offices all around the globe need to be able to install this application.</p> <p>The application is actually a plugin to Excel and we have an automatic installer based on Setuptools' easy_install that ensures that all a project's dependancies are automatically installed or updated any time a user switches on their Excel. It all works very elegantly as users are seldom aware of all the installation which occurs entirely in the background.</p> <p>Unfortunately we are expanding and opening new offices which all have different proxy settings. These settings seem to change from day to day so we cannot keep up with the outsourced security guys who change stuff without telling us. It sucks but we just have to work around it. </p> <p>I want to programatically detect the system-wide proxy settings on the Windows workstations our users run: </p> <p>Everybody in the organisazation runs Windows XP and Internet Explorer. I've verified that everybody can download our stuff from IE without problems regardless of where they are int the world. </p> <p>So all I need to do is detect what proxy settings IE is using and make Setuptools use those settings. Theoretically all of this information should be in the Registry.. but is there a better way to find it that is guaranteed not to change with people upgrade IE? For example is there a Windows API call I can use to discover the proxy settings? </p> <p>In summary:</p> <ul> <li>We use Python 2.4.4 on Windows XP</li> <li>We need to detect the Internet Explorer proxy settings (e.g. host, port and Proxy type)</li> <li>I'm going to use this information to dynamically re-configure easy_install so that it can download the egg files via the proxy. </li> </ul> <p>UPDATE0: </p> <p>I forgot one important detail: Each site has an auto-config "pac" file. </p> <p>There's a key in Windows\CurrentVersion\InternetSettings\AutoConfigURL which points to a HTTP document on a local server which contains what looks like a javascript file.</p> <p>The pac script is basically a series of nested if-statements which compare URLs against a regexp and then eventually return the hostname of the chosen proxy-server. The script is a single javascript function called FindProxyForURL(url, host) </p> <p>The challenge is therefore to find out for any given server which proxy to use. The only 100% guaranteed way to do this is to look up the pac file and call the Javascript function from Python. </p> <p>Any suggestions? Is there a more elegant way to do this?</p>
4
2009-07-01T09:33:51Z
1,068,303
<p>As far as I know, In a Windows environment, if no proxy environment variables are set, proxy settings are obtained from the registry's Internet Settings section. . Isn't it enough?</p> <p>Or u can get something useful info from registry: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyServer</p> <p>Edit:<br /> sorry for don't know how to format comment's source code, I repost it here.</p> <pre><code>&gt;&gt;&gt; import win32com.client &gt;&gt;&gt; js = win32com.client.Dispatch('MSScriptControl.ScriptControl') &gt;&gt;&gt; js.Language = 'JavaScript' &gt;&gt;&gt; js.AddCode('function add(a, b) {return a+b;}') &gt;&gt;&gt; js.Run('add', 1, 2) 3 </code></pre>
3
2009-07-01T09:59:40Z
[ "python", "windows", "networking", "proxy", "setuptools" ]
Programmatically detect system-proxy settings on Windows XP with Python
1,068,212
<p>I develop a critical application used by a multi-national company. Users in offices all around the globe need to be able to install this application.</p> <p>The application is actually a plugin to Excel and we have an automatic installer based on Setuptools' easy_install that ensures that all a project's dependancies are automatically installed or updated any time a user switches on their Excel. It all works very elegantly as users are seldom aware of all the installation which occurs entirely in the background.</p> <p>Unfortunately we are expanding and opening new offices which all have different proxy settings. These settings seem to change from day to day so we cannot keep up with the outsourced security guys who change stuff without telling us. It sucks but we just have to work around it. </p> <p>I want to programatically detect the system-wide proxy settings on the Windows workstations our users run: </p> <p>Everybody in the organisazation runs Windows XP and Internet Explorer. I've verified that everybody can download our stuff from IE without problems regardless of where they are int the world. </p> <p>So all I need to do is detect what proxy settings IE is using and make Setuptools use those settings. Theoretically all of this information should be in the Registry.. but is there a better way to find it that is guaranteed not to change with people upgrade IE? For example is there a Windows API call I can use to discover the proxy settings? </p> <p>In summary:</p> <ul> <li>We use Python 2.4.4 on Windows XP</li> <li>We need to detect the Internet Explorer proxy settings (e.g. host, port and Proxy type)</li> <li>I'm going to use this information to dynamically re-configure easy_install so that it can download the egg files via the proxy. </li> </ul> <p>UPDATE0: </p> <p>I forgot one important detail: Each site has an auto-config "pac" file. </p> <p>There's a key in Windows\CurrentVersion\InternetSettings\AutoConfigURL which points to a HTTP document on a local server which contains what looks like a javascript file.</p> <p>The pac script is basically a series of nested if-statements which compare URLs against a regexp and then eventually return the hostname of the chosen proxy-server. The script is a single javascript function called FindProxyForURL(url, host) </p> <p>The challenge is therefore to find out for any given server which proxy to use. The only 100% guaranteed way to do this is to look up the pac file and call the Javascript function from Python. </p> <p>Any suggestions? Is there a more elegant way to do this?</p>
4
2009-07-01T09:33:51Z
1,068,484
<p>Here's a sample that should create a bullet green (proxy enable) or red (proxy disable) in your systray</p> <p>It shows how to read and write in windows registry</p> <p>it uses gtk</p> <pre><code>#!/usr/bin/env python import gobject import gtk from _winreg import * class ProxyNotifier: def __init__(self): self.trayIcon = gtk.StatusIcon() self.updateIcon() #set callback on right click to on_right_click self.trayIcon.connect('popup-menu', self.on_right_click) gobject.timeout_add(1000, self.checkStatus) def isProxyEnabled(self): aReg = ConnectRegistry(None,HKEY_CURRENT_USER) aKey = OpenKey(aReg, r"Software\Microsoft\Windows\CurrentVersion\Internet Settings") subCount, valueCount, lastModified = QueryInfoKey(aKey) for i in range(valueCount): try: n,v,t = EnumValue(aKey,i) if n == 'ProxyEnable': return v and True or False except EnvironmentError: break CloseKey(aKey) def invertProxyEnableState(self): aReg = ConnectRegistry(None,HKEY_CURRENT_USER) aKey = OpenKey(aReg, r"Software\Microsoft\Windows\CurrentVersion\Internet Settings", 0, KEY_WRITE) if self.isProxyEnabled() : val = 0 else: val = 1 try: SetValueEx(aKey,"ProxyEnable",0, REG_DWORD, val) except EnvironmentError: print "Encountered problems writing into the Registry..." CloseKey(aKey) def updateIcon(self): if self.isProxyEnabled(): icon=gtk.STOCK_YES else: icon=gtk.STOCK_NO self.trayIcon.set_from_stock(icon) def checkStatus(self): self.updateIcon() return True def on_right_click(self, data, event_button, event_time): self.invertProxyEnableState() self.updateIcon() if __name__ == '__main__': proxyNotifier = ProxyNotifier() gtk.main() </code></pre>
4
2009-07-01T10:54:28Z
[ "python", "windows", "networking", "proxy", "setuptools" ]
Python unittest: how to run only part of a test file?
1,068,246
<p>I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class.</p> <p>Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the best way would be with a command-line argument, ie "<code>./tests.py --offline</code>" or something like that), so I could run most of the tests often and quickly and the whole set once in a while, when I have time.</p> <p>For now, I just use <code>unittest.main()</code> to start the tests.</p> <p>Thanks.</p>
44
2009-07-01T09:40:32Z
1,068,275
<p>Look into using a dedicated testrunner, like py.test, nose or possibly even zope.testing. They all have command line options for selecting tests.</p> <p>Look for example as Nose: <a href="https://pypi.python.org/pypi/nose/1.3.0" rel="nofollow">https://pypi.python.org/pypi/nose/1.3.0</a></p>
2
2009-07-01T09:51:09Z
[ "python", "unit-testing", "pyunit" ]
Python unittest: how to run only part of a test file?
1,068,246
<p>I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class.</p> <p>Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the best way would be with a command-line argument, ie "<code>./tests.py --offline</code>" or something like that), so I could run most of the tests often and quickly and the whole set once in a while, when I have time.</p> <p>For now, I just use <code>unittest.main()</code> to start the tests.</p> <p>Thanks.</p>
44
2009-07-01T09:40:32Z
1,068,339
<p>You have basically two ways to do it:</p> <ol> <li>Define your own suite of tests for the class</li> <li>Create mock classes of the cluster connection that will return actual data.</li> </ol> <p>I am a strong proponent of he second approach; a unit test <em>should</em> test only a very unit of code, and not complex systems (like databases or clusters). But I understand that it is not always possible; sometimes, creating mock ups is simply too expensive, or the goal of the test is really in the complex system.</p> <p>Back to option (1), you can proceed in this way:</p> <pre><code>suite = unittest.TestSuite() suite.addTest(MyUnitTestClass('quickRunningTest')) suite.addTest(MyUnitTestClass('otherTest')) </code></pre> <p>and then passing the suite to the test runner:</p> <pre><code>unittest.TextTestRunner().run(suite) </code></pre> <p>More information on the python documentation: <a href="http://docs.python.org/library/unittest.html#testsuite-objects">http://docs.python.org/library/unittest.html#testsuite-objects</a></p>
6
2009-07-01T10:12:52Z
[ "python", "unit-testing", "pyunit" ]
Python unittest: how to run only part of a test file?
1,068,246
<p>I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class.</p> <p>Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the best way would be with a command-line argument, ie "<code>./tests.py --offline</code>" or something like that), so I could run most of the tests often and quickly and the whole set once in a while, when I have time.</p> <p>For now, I just use <code>unittest.main()</code> to start the tests.</p> <p>Thanks.</p>
44
2009-07-01T09:40:32Z
1,068,366
<p>The default <code>unittest.main()</code> uses the default test loader to make a TestSuite out of the module in which main is running.</p> <p>You don't have to use this default behavior.</p> <p>You can, for example, make three <a href="http://docs.python.org/library/unittest.html#unittest.TestSuite">unittest.TestSuite</a> instances.</p> <ol> <li><p>The "fast" subset.</p> <pre><code>fast = TestSuite() fast.addTests( TestFastThis ) fast.addTests( TestFastThat ) </code></pre></li> <li><p>The "slow" subset.</p> <pre><code>slow = TestSuite() slow.addTests( TestSlowAnother ) slow.addTests( TestSlowSomeMore ) </code></pre></li> <li><p>The "whole" set.</p> <pre><code>alltests = unittest.TestSuite([fast, slow]) </code></pre></li> </ol> <p>Note that I've adjusted the TestCase names to indicate Fast vs. Slow. You can subclass unittest.TestLoader to parse the names of classes and create multiple loaders.</p> <p>Then your main program can parse command-line arguments with <a href="http://docs.python.org/library/optparse.html">optparse</a> or <a href="https://docs.python.org/dev/library/argparse.html">argparse</a> (available since 2.7 or 3.2) to pick which suite you want to run, fast, slow or all.</p> <p>Or, you can trust that <code>sys.argv[1]</code> is one of three values and use something as simple as this</p> <pre><code>if __name__ == "__main__": suite = eval(sys.argv[1]) # Be careful with this line! unittest.TextTestRunner().run(suite) </code></pre>
38
2009-07-01T10:23:27Z
[ "python", "unit-testing", "pyunit" ]
Python unittest: how to run only part of a test file?
1,068,246
<p>I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class.</p> <p>Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the best way would be with a command-line argument, ie "<code>./tests.py --offline</code>" or something like that), so I could run most of the tests often and quickly and the whole set once in a while, when I have time.</p> <p>For now, I just use <code>unittest.main()</code> to start the tests.</p> <p>Thanks.</p>
44
2009-07-01T09:40:32Z
12,696,073
<p>Actually, one can pass the names of the test case as sys.argv and only those cases will be tested.</p> <p>For instance, suppose you have</p> <pre><code>class TestAccount(unittest.TestCase): ... class TestCustomer(unittest.TestCase): ... class TestShipping(unittest.TestCase): ... account = TestAccount customer = TestCustomer shipping = TestShipping </code></pre> <p>You can call </p> <pre><code>python test.py account </code></pre> <p>to have only account tests, or even</p> <pre><code>$ python test.py account customer </code></pre> <p>to have both cases tested</p>
8
2012-10-02T18:28:18Z
[ "python", "unit-testing", "pyunit" ]
Python unittest: how to run only part of a test file?
1,068,246
<p>I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class.</p> <p>Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the best way would be with a command-line argument, ie "<code>./tests.py --offline</code>" or something like that), so I could run most of the tests often and quickly and the whole set once in a while, when I have time.</p> <p>For now, I just use <code>unittest.main()</code> to start the tests.</p> <p>Thanks.</p>
44
2009-07-01T09:40:32Z
17,097,698
<p>Or you can make use of the <code>unittest.SkipTest()</code> function. Example, add a <code>skipOrRunTest</code> method to your test class like this:</p> <pre><code>def skipOrRunTest(self,testType): #testsToRun = 'ALL' #testsToRun = 'testType1, testType2, testType3, testType4,...etc' #testsToRun = 'testType1' #testsToRun = 'testType2' #testsToRun = 'testType3' testsToRun = 'testType4' if ((testsToRun == 'ALL') or (testType in testsToRun)): return True else: print "SKIPPED TEST because:\n\t testSuite '" + testType + "' NOT IN testsToRun['" + testsToRun + "']" self.skipTest("skipppy!!!") </code></pre> <p>Then add a call to this skipOrRunTest method to the very beginning of each of your unit tests like this:</p> <pre><code>def testType4(self): self.skipOrRunTest('testType4') </code></pre>
0
2013-06-13T21:46:36Z
[ "python", "unit-testing", "pyunit" ]
Python unittest: how to run only part of a test file?
1,068,246
<p>I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class.</p> <p>Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the best way would be with a command-line argument, ie "<code>./tests.py --offline</code>" or something like that), so I could run most of the tests often and quickly and the whole set once in a while, when I have time.</p> <p>For now, I just use <code>unittest.main()</code> to start the tests.</p> <p>Thanks.</p>
44
2009-07-01T09:40:32Z
17,817,391
<p>To run only a single specific test you can use:</p> <pre><code>$ python -m unittest test_module.TestClass.test_method </code></pre> <p>More information <a href="http://pythontesting.net/framework/specify-test-unittest-nosetests-pytest/">here</a></p>
59
2013-07-23T17:48:07Z
[ "python", "unit-testing", "pyunit" ]
Python unittest: how to run only part of a test file?
1,068,246
<p>I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class.</p> <p>Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the best way would be with a command-line argument, ie "<code>./tests.py --offline</code>" or something like that), so I could run most of the tests often and quickly and the whole set once in a while, when I have time.</p> <p>For now, I just use <code>unittest.main()</code> to start the tests.</p> <p>Thanks.</p>
44
2009-07-01T09:40:32Z
24,427,772
<p>Since you use <code>unittest.main()</code> you can just run <code>python tests.py --help</code> to get the documentation:</p> <pre><code>Usage: tests.py [options] [test] [...] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output -f, --failfast Stop on first failure -c, --catch Catch control-C and display results -b, --buffer Buffer stdout and stderr during test runs Examples: tests.py - run default set of tests tests.py MyTestSuite - run suite 'MyTestSuite' tests.py MyTestCase.testSomething - run MyTestCase.testSomething tests.py MyTestCase - run all 'test*' test methods in MyTestCase </code></pre> <p>That is, you can simple do</p> <pre><code>python tests.py TestClass.test_method </code></pre>
4
2014-06-26T10:10:49Z
[ "python", "unit-testing", "pyunit" ]
Python unittest: how to run only part of a test file?
1,068,246
<p>I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class.</p> <p>Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the best way would be with a command-line argument, ie "<code>./tests.py --offline</code>" or something like that), so I could run most of the tests often and quickly and the whole set once in a while, when I have time.</p> <p>For now, I just use <code>unittest.main()</code> to start the tests.</p> <p>Thanks.</p>
44
2009-07-01T09:40:32Z
30,187,488
<p>I have found another way to select the test_* methods that I only want to run by adding an attribute to them. You basically use a metaclass to decorate the callables inside the TestCase class that have the StepDebug attribute with a unittest.skip decorator. More info on</p> <p><a href="http://stackoverflow.com/q/30121111/3257551">Skipping all unit tests but one in Python by using decorators and metaclasses</a></p> <p>I don't know if it is a better solution than those above I am just providing it as an option.</p>
0
2015-05-12T09:58:50Z
[ "python", "unit-testing", "pyunit" ]
Python unittest: how to run only part of a test file?
1,068,246
<p>I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class.</p> <p>Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the best way would be with a command-line argument, ie "<code>./tests.py --offline</code>" or something like that), so I could run most of the tests often and quickly and the whole set once in a while, when I have time.</p> <p>For now, I just use <code>unittest.main()</code> to start the tests.</p> <p>Thanks.</p>
44
2009-07-01T09:40:32Z
33,132,449
<p>Haven't found a nice way to do this before, so sharing here.</p> <p>Goal: Get a set of test files together so they can be run as a unit, but we can still select any one of them to run by itself. </p> <p>Problem: the discover method does not allow easy selection of a single test case to run.</p> <p>Design: see below. This <em>flattens</em> the namespace so can select by TestCase class name, and leave off the the "tests1.test_core" prefix:</p> <pre><code>./run-tests TestCore.test_fmap </code></pre> <p>Code</p> <pre><code> test_module_names = [ 'tests1.test_core', 'tests2.test_other', 'tests3.test_foo', ] loader = unittest.defaultTestLoader if args: alltests = unittest.TestSuite() for a in args: for m in test_module_names: try: alltests.addTest( loader.loadTestsFromName( m+'.'+a ) ) except AttributeError as e: continue else: alltests = loader.loadTestsFromNames( test_module_names ) runner = unittest.TextTestRunner( verbosity = opt.verbose ) runner.run( alltests ) </code></pre>
0
2015-10-14T18:01:27Z
[ "python", "unit-testing", "pyunit" ]
Python unittest: how to run only part of a test file?
1,068,246
<p>I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class.</p> <p>Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the best way would be with a command-line argument, ie "<code>./tests.py --offline</code>" or something like that), so I could run most of the tests often and quickly and the whole set once in a while, when I have time.</p> <p>For now, I just use <code>unittest.main()</code> to start the tests.</p> <p>Thanks.</p>
44
2009-07-01T09:40:32Z
34,146,740
<p>I tried @slott's answer:</p> <pre><code>if __name__ == "__main__": suite = eval(sys.argv[1]) # Be careful with this line! unittest.TextTestRunner().run(suite) </code></pre> <p>But that gave me the following error:</p> <pre><code>Traceback (most recent call last): File "functional_tests.py", line 178, in &lt;module&gt; unittest.TextTestRunner().run(suite) File "/usr/lib/python2.7/unittest/runner.py", line 151, in run test(result) File "/usr/lib/python2.7/unittest/case.py", line 188, in __init__ testMethod = getattr(self, methodName) TypeError: getattr(): attribute name must be string </code></pre> <p>The following worked for me:</p> <pre><code>if __name__ == "__main__": test_class = eval(sys.argv[1]) suite = unittest.TestLoader().loadTestsFromTestCase(test_class) unittest.TextTestRunner().run(suite) </code></pre>
1
2015-12-08T02:04:02Z
[ "python", "unit-testing", "pyunit" ]
Using SimpleXMLTreeBuilder in elementtree
1,068,510
<p>I have been developing an application with django and elementtree and while deploying it to the production server i have found out it is running python 2.4. I have been able to bundle elementtree but now i am getting the error:</p> <pre><code>"No module named expat; use SimpleXMLTreeBuilder instead" </code></pre> <p>Unfortunately i cannot upgrade python so im stuck with what i got. How do i use SimpleXMLTreeBuilder as the parser and/or will i need to rewrite code?</p>
4
2009-07-01T11:02:51Z
1,069,424
<p>Assuming you're now using <code>elementtree.XMLTreeBuilder</code>, just try this instead:</p> <pre><code>from elementtree import SimpleXMLTreeBuilder as XMLTreeBuilder </code></pre> <p>It tries to provide exactly the same functionality but using xmllib instead of expat. If that also fails, BTW, try:</p> <pre><code>from elementtree import SgmlopXMLTreeBuilder as XMLTreeBuilder </code></pre> <p>to attempt to use yet another implementation, this one based on sgmlop instead.</p>
0
2009-07-01T14:27:22Z
[ "python", "django", "elementtree" ]
Using SimpleXMLTreeBuilder in elementtree
1,068,510
<p>I have been developing an application with django and elementtree and while deploying it to the production server i have found out it is running python 2.4. I have been able to bundle elementtree but now i am getting the error:</p> <pre><code>"No module named expat; use SimpleXMLTreeBuilder instead" </code></pre> <p>Unfortunately i cannot upgrade python so im stuck with what i got. How do i use SimpleXMLTreeBuilder as the parser and/or will i need to rewrite code?</p>
4
2009-07-01T11:02:51Z
1,070,269
<blockquote> <p>from elementtree import SimpleXMLTreeBuilder as XMLTreeBuilder</p> </blockquote> <p>Ok, it has slightly changed now:</p> <pre><code>Traceback (most recent call last): File "C:\Python26\tests\xml.py", line 12, in &lt;module&gt; doc = elementtree.ElementTree.parse("foo.xml") File "C:\Python26\lib\site-packages\elementtree\ElementTree.py", line 908, in parse tree = parser_api.parse(source) File "C:\Python26\lib\site-packages\elementtree\ElementTree.py", line 169, in parse parser = XMLTreeBuilder() File "C:\Python26\lib\site-packages\elementtree\ElementTree.py", line 1165, in __init__ "No module named expat; use SimpleXMLTreeBuilder instead" ImportError: No module named expat; use SimpleXMLTreeBuilder instead </code></pre> <p>I think it was statically linked with older version of Python or something. Is there an easy way to attach XML parser to Python 2.6? Some libraries seem to only work with older versions 8(</p>
0
2009-07-01T17:03:08Z
[ "python", "django", "elementtree" ]
Using SimpleXMLTreeBuilder in elementtree
1,068,510
<p>I have been developing an application with django and elementtree and while deploying it to the production server i have found out it is running python 2.4. I have been able to bundle elementtree but now i am getting the error:</p> <pre><code>"No module named expat; use SimpleXMLTreeBuilder instead" </code></pre> <p>Unfortunately i cannot upgrade python so im stuck with what i got. How do i use SimpleXMLTreeBuilder as the parser and/or will i need to rewrite code?</p>
4
2009-07-01T11:02:51Z
2,067,177
<p>If you have third party module that wants to use ElementTree (and XMLTreeBuilder by dependency) you can change ElementTree's XMLTreeBuilder definition to the one provided by SimpleXMLTreeBuilder like so:</p> <pre><code>from xml.etree import ElementTree # part of python distribution from elementtree import SimpleXMLTreeBuilder # part of your codebase ElementTree.XMLTreeBuilder = SimpleXMLTreeBuilder.TreeBuilder </code></pre> <p>Now ElementTree will always use the SimpleXMLTreeBuilder whenever it's called.</p> <p>See also: <a href="http://groups.google.com/group/google-appengine/browse_thread/thread/b7399a91c9525c97">http://groups.google.com/group/google-appengine/browse_thread/thread/b7399a91c9525c97</a></p>
6
2010-01-14T19:59:21Z
[ "python", "django", "elementtree" ]
Using SimpleXMLTreeBuilder in elementtree
1,068,510
<p>I have been developing an application with django and elementtree and while deploying it to the production server i have found out it is running python 2.4. I have been able to bundle elementtree but now i am getting the error:</p> <pre><code>"No module named expat; use SimpleXMLTreeBuilder instead" </code></pre> <p>Unfortunately i cannot upgrade python so im stuck with what i got. How do i use SimpleXMLTreeBuilder as the parser and/or will i need to rewrite code?</p>
4
2009-07-01T11:02:51Z
10,235,911
<p>We ran into this same problem using python version 2.6.4 on CentOS 5.5.</p> <p>The issue happens when the expat class attempts to load the pyexpat modules, see /usr/lib64/python2.6/xml/parsers/expat.py</p> <p>Looking inside of /usr/lib64/python2.6/lib-dynload/, I didn't see the "pyexpat.so" shared object. However, I <em>did</em> see it on another machine, which wasn't having the problem.</p> <p>I compared the python versions (yum list 'python*') and identified that the properly functioning machine had python 2.6.5. Running 'yum update python26' fixed the issue for me.</p> <p>If that doesn't work for you and you want a slapstick solution, you can copy the SO file into your dynamic load path. </p>
1
2012-04-19T20:05:48Z
[ "python", "django", "elementtree" ]
Using SimpleXMLTreeBuilder in elementtree
1,068,510
<p>I have been developing an application with django and elementtree and while deploying it to the production server i have found out it is running python 2.4. I have been able to bundle elementtree but now i am getting the error:</p> <pre><code>"No module named expat; use SimpleXMLTreeBuilder instead" </code></pre> <p>Unfortunately i cannot upgrade python so im stuck with what i got. How do i use SimpleXMLTreeBuilder as the parser and/or will i need to rewrite code?</p>
4
2009-07-01T11:02:51Z
20,462,530
<p>I have same error as you when I developed on Solaris &amp; python 2.7.2. I fixed this issue after I installed the python <code>expat</code> package by using pkgin. See if the solution above can give you any idea.</p>
0
2013-12-09T03:17:43Z
[ "python", "django", "elementtree" ]
Skip steps on a django FormWizard
1,068,572
<p>I have an application where there is a FormWizard with 5 steps, one of them should only appear when some conditions are satisfied.</p> <p>The form is for a payment wizard on a on-line cart, one of the steps should only show when there are promotions available for piking one, but when there are no promotions i want to skip that step instead of showing an empty list of promotions.</p> <p>So I want to have 2 possible flows:</p> <pre><code>step1 - step2 - step3 step1 - step3 </code></pre>
2
2009-07-01T11:21:27Z
1,079,855
<p>The hook method <a href="http://docs.djangoproject.com/en/dev/ref/contrib/formtools/form-wizard/#django.contrib.formtools.wizard.FormWizard.process%5Fstep">process_step()</a> gives you exactly that opportunity. After the form is validated you can modify the <strong>self.form_list</strong> variable, and delete the forms you don't need.</p> <p>Needles to say if you logic is very complicated, you are better served creating separate views for each step/form, and forgoing the FormWizard altogether.</p>
5
2009-07-03T15:27:33Z
[ "python", "django", "formwizard" ]
Skip steps on a django FormWizard
1,068,572
<p>I have an application where there is a FormWizard with 5 steps, one of them should only appear when some conditions are satisfied.</p> <p>The form is for a payment wizard on a on-line cart, one of the steps should only show when there are promotions available for piking one, but when there are no promotions i want to skip that step instead of showing an empty list of promotions.</p> <p>So I want to have 2 possible flows:</p> <pre><code>step1 - step2 - step3 step1 - step3 </code></pre>
2
2009-07-01T11:21:27Z
1,144,537
<p>I did it other way, overriding the render_template method. Here my solution. I didn't know about the process_step()...</p> <pre><code>def render_template(self, request, form, previous_fields, step, context): if not step == 0: # A workarround to find the type value! attr = 'name="0-type" value=' attr_pos = previous_fields.find(attr) + len(attr) val = previous_fields[attr_pos:attr_pos+4] type = int(val.split('"')[1]) if step == 2 and (not type == 1 and not type == 2 and not type == 3): form = self.get_form(step+1) return super(ProductWizard, self).render_template(request, form, previous_fields, step+1, context) return super(ProductWizard, self).render_template(request, form, previous_fields, step, context) </code></pre>
0
2009-07-17T17:04:43Z
[ "python", "django", "formwizard" ]
Skip steps on a django FormWizard
1,068,572
<p>I have an application where there is a FormWizard with 5 steps, one of them should only appear when some conditions are satisfied.</p> <p>The form is for a payment wizard on a on-line cart, one of the steps should only show when there are promotions available for piking one, but when there are no promotions i want to skip that step instead of showing an empty list of promotions.</p> <p>So I want to have 2 possible flows:</p> <pre><code>step1 - step2 - step3 step1 - step3 </code></pre>
2
2009-07-01T11:21:27Z
23,078,874
<p>To make certain forms optional you can introduce conditionals in the list of forms you pass to the FormView in your urls.py:</p> <pre><code>contact_forms = [ContactForm1, ContactForm2] urlpatterns = patterns('', (r'^contact/$', ContactWizard.as_view(contact_forms, condition_dict={'1': show_message_form_condition} )), ) </code></pre> <p>For a full example see the Django docs: <a href="https://docs.djangoproject.com/en/1.5/ref/contrib/formtools/form-wizard/#conditionally-view-skip-specific-steps" rel="nofollow">https://docs.djangoproject.com/en/1.5/ref/contrib/formtools/form-wizard/#conditionally-view-skip-specific-steps</a></p>
0
2014-04-15T08:54:10Z
[ "python", "django", "formwizard" ]
Django way to do conditional formatting
1,068,573
<p>What is the correct way to do conditional formatting in Django?</p> <p>I have a model that contains a date field, and I would like to display a list of records, but colour the rows depending on the value of that date field. For example, records that match today's date I want to be yellow, records that is before today I want green and ones after I want red.</p> <p>Somewhere in Django you will need to do that comparison, comparing the current date with the date in the record.</p> <p>I can see three different places that comparison could be done:</p> <ol> <li>Add a method to my model, for example, status(), that returns either 'past', 'present', 'future' and then use that in the template to colour the rows.</li> <li>In the view instead of returning a queryset to the template, pre-process the list and compare each record, build a new dict containing the 'past', 'present' and 'future' values to be used in the template</li> <li>Create a new template tag that does the comparison.</li> </ol> <p>Which of these methods is the correct Django way of doing it? It sounds like conditional formating is something that would come up quite often, and since you can't do arbitrary comparisons in the template some other solution is needed.</p> <p>The same would apply for simpler formatting rules, for example, if I wanted to display a list of student grades, and I wanted to make the ones higher than 80% green and the ones below 30% red.</p>
5
2009-07-01T11:21:30Z
1,068,601
<p>Since you are doing static comparison (no queries needed), you should go for the most DRY and easy to implement option. In this case, I would go for option 4, make a template filter. Then you could do value|filter to get the class you would need to set the background colour. Template filters are actually a bit simpler than template tags to implement.</p>
1
2009-07-01T11:27:20Z
[ "python", "django", "formatting", "django-templates" ]
Django way to do conditional formatting
1,068,573
<p>What is the correct way to do conditional formatting in Django?</p> <p>I have a model that contains a date field, and I would like to display a list of records, but colour the rows depending on the value of that date field. For example, records that match today's date I want to be yellow, records that is before today I want green and ones after I want red.</p> <p>Somewhere in Django you will need to do that comparison, comparing the current date with the date in the record.</p> <p>I can see three different places that comparison could be done:</p> <ol> <li>Add a method to my model, for example, status(), that returns either 'past', 'present', 'future' and then use that in the template to colour the rows.</li> <li>In the view instead of returning a queryset to the template, pre-process the list and compare each record, build a new dict containing the 'past', 'present' and 'future' values to be used in the template</li> <li>Create a new template tag that does the comparison.</li> </ol> <p>Which of these methods is the correct Django way of doing it? It sounds like conditional formating is something that would come up quite often, and since you can't do arbitrary comparisons in the template some other solution is needed.</p> <p>The same would apply for simpler formatting rules, for example, if I wanted to display a list of student grades, and I wanted to make the ones higher than 80% green and the ones below 30% red.</p>
5
2009-07-01T11:21:30Z
1,068,606
<p>I had a very similar requirement; as this is pretty connected to the business logic, I have added a model method to manage this kind of information, to be used then in the template:</p> <pre><code>{% if not bug.within_due_date %}bgcolor="OrangeRed"{% endif %} </code></pre> <p>It could also be obtained through a template tag or filter; but in my case, I felt the best place for the logic was inside the model; I would suggest you analyzing it in the same way.</p>
3
2009-07-01T11:28:14Z
[ "python", "django", "formatting", "django-templates" ]
Django way to do conditional formatting
1,068,573
<p>What is the correct way to do conditional formatting in Django?</p> <p>I have a model that contains a date field, and I would like to display a list of records, but colour the rows depending on the value of that date field. For example, records that match today's date I want to be yellow, records that is before today I want green and ones after I want red.</p> <p>Somewhere in Django you will need to do that comparison, comparing the current date with the date in the record.</p> <p>I can see three different places that comparison could be done:</p> <ol> <li>Add a method to my model, for example, status(), that returns either 'past', 'present', 'future' and then use that in the template to colour the rows.</li> <li>In the view instead of returning a queryset to the template, pre-process the list and compare each record, build a new dict containing the 'past', 'present' and 'future' values to be used in the template</li> <li>Create a new template tag that does the comparison.</li> </ol> <p>Which of these methods is the correct Django way of doing it? It sounds like conditional formating is something that would come up quite often, and since you can't do arbitrary comparisons in the template some other solution is needed.</p> <p>The same would apply for simpler formatting rules, for example, if I wanted to display a list of student grades, and I wanted to make the ones higher than 80% green and the ones below 30% red.</p>
5
2009-07-01T11:21:30Z
1,068,616
<p>I'm a big fan of putting ALL "business" logic in the view function and ALL presentation in the templates/CSS.</p> <p>Option 1 is ideal. You return a list of pairs: ( date, state ), where the state is the class name ("past", "present", "future").</p> <p>Your template then uses the state information as the class for a <code>&lt;span&gt;</code>. Your CSS then provides the color coding for that span.</p> <p>You are now free to change the rules without breaking the template. You can change the CSS without touching HTML or Python code.</p> <pre><code>{% for date,state in the_date_list %} &lt;span class="{{state}}"&gt;date&lt;/span&gt; {% endfor %} </code></pre>
8
2009-07-01T11:30:08Z
[ "python", "django", "formatting", "django-templates" ]
Django way to do conditional formatting
1,068,573
<p>What is the correct way to do conditional formatting in Django?</p> <p>I have a model that contains a date field, and I would like to display a list of records, but colour the rows depending on the value of that date field. For example, records that match today's date I want to be yellow, records that is before today I want green and ones after I want red.</p> <p>Somewhere in Django you will need to do that comparison, comparing the current date with the date in the record.</p> <p>I can see three different places that comparison could be done:</p> <ol> <li>Add a method to my model, for example, status(), that returns either 'past', 'present', 'future' and then use that in the template to colour the rows.</li> <li>In the view instead of returning a queryset to the template, pre-process the list and compare each record, build a new dict containing the 'past', 'present' and 'future' values to be used in the template</li> <li>Create a new template tag that does the comparison.</li> </ol> <p>Which of these methods is the correct Django way of doing it? It sounds like conditional formating is something that would come up quite often, and since you can't do arbitrary comparisons in the template some other solution is needed.</p> <p>The same would apply for simpler formatting rules, for example, if I wanted to display a list of student grades, and I wanted to make the ones higher than 80% green and the ones below 30% red.</p>
5
2009-07-01T11:21:30Z
7,217,889
<p>you can also take a look at Django's reference for built in Formatting and Filtering tags. It sure has what you are looking for and more and it's a good link to have bookmarked.</p> <p>You can take a look at it <a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs" rel="nofollow">here</a>.</p>
0
2011-08-27T22:50:52Z
[ "python", "django", "formatting", "django-templates" ]
Is there a python module compatible with Google Apps Engine's new "Tasks"
1,068,690
<p>I'm writing a Python application, that I want to later migrate to GAE. The new "Task Queues" API fulfills a requirement of my app, and I want to simulate it locally until I have the time to migrate the whole thing to GAE.</p> <p>Does anyone know of a compatible module I can run locally?</p>
0
2009-07-01T11:43:50Z
1,844,774
<p>Given the explicitly experimental nature of the thing, there's certainly nothing <em>compatible</em> in existence at this time. And obviously even if there were, Google pretty much says <a href="http://code.google.com/appengine/docs/python/taskqueue/tasks.html" rel="nofollow">"we're going to change the API!"</a> in their warning about it, so anything compatible now would not be compatible when the time comes to migrate.</p>
1
2009-12-04T04:04:06Z
[ "python", "google-app-engine", "migration", "task" ]
Is there a python module compatible with Google Apps Engine's new "Tasks"
1,068,690
<p>I'm writing a Python application, that I want to later migrate to GAE. The new "Task Queues" API fulfills a requirement of my app, and I want to simulate it locally until I have the time to migrate the whole thing to GAE.</p> <p>Does anyone know of a compatible module I can run locally?</p>
0
2009-07-01T11:43:50Z
2,441,810
<p>Since my original question, I've found two projects that aim to release the vendor-lock-in of GAE:</p> <ol> <li>AppScale - <a href="http://code.google.com/p/appscale/" rel="nofollow">http://code.google.com/p/appscale/</a></li> <li>TyphoonAE - <a href="http://code.google.com/p/typhoonae/" rel="nofollow">http://code.google.com/p/typhoonae/</a></li> </ol> <p>There is also the GAE Testbed for easier testing: <a href="http://code.google.com/p/gae-testbed/" rel="nofollow">http://code.google.com/p/gae-testbed/</a></p>
0
2010-03-14T10:18:50Z
[ "python", "google-app-engine", "migration", "task" ]
Problem using os.system() with sed command
1,068,812
<p>I'm writing a small method to replace some text in a file. The only argument I need is the new text, as it is always the same file and text to be replaced.</p> <p>I'm having a problem using the os.system() call, when I try to use the argument of the method</p> <p>If I use a string like below, everything runs ok:</p> <pre><code>stringId = "GRRRRRRRRR" cmd="sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" os.system(cmd) </code></pre> <p>Now, if i try to give a string as a parameter like below, the command is not executed. I do a print to see if the command is correct, and it is. I can even execute it with success if I copy / paste to my shell</p> <pre><code>import os def updateExportConfigId(id): stringId = "%s" % id cmd= "sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" print "command is " + cmd os.system(cmd) </code></pre> <p>Does anyone knows what is wrong?</p> <p>Thanks</p>
2
2009-07-01T12:11:38Z
1,068,893
<p>To help you debug it, try adding:</p> <pre><code>print repr(cmd) </code></pre> <p>It might be that some special characters slipped into the command that normal print is hiding when you copy and paste it.</p>
1
2009-07-01T12:27:57Z
[ "python" ]
Problem using os.system() with sed command
1,068,812
<p>I'm writing a small method to replace some text in a file. The only argument I need is the new text, as it is always the same file and text to be replaced.</p> <p>I'm having a problem using the os.system() call, when I try to use the argument of the method</p> <p>If I use a string like below, everything runs ok:</p> <pre><code>stringId = "GRRRRRRRRR" cmd="sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" os.system(cmd) </code></pre> <p>Now, if i try to give a string as a parameter like below, the command is not executed. I do a print to see if the command is correct, and it is. I can even execute it with success if I copy / paste to my shell</p> <pre><code>import os def updateExportConfigId(id): stringId = "%s" % id cmd= "sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" print "command is " + cmd os.system(cmd) </code></pre> <p>Does anyone knows what is wrong?</p> <p>Thanks</p>
2
2009-07-01T12:11:38Z
1,068,962
<p>Maybe some indentation problem?</p> <p>The following works correctly:</p> <pre><code>import os def updateExportConfigId(id): stringId = "%s" % id cmd= "sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' test.dat &gt; test.new" print "command is " + cmd os.system(cmd) updateExportConfigId("adsf") </code></pre> <p>Also do not use reserved words (<code>id</code>) as variables.</p>
0
2009-07-01T12:41:16Z
[ "python" ]
Problem using os.system() with sed command
1,068,812
<p>I'm writing a small method to replace some text in a file. The only argument I need is the new text, as it is always the same file and text to be replaced.</p> <p>I'm having a problem using the os.system() call, when I try to use the argument of the method</p> <p>If I use a string like below, everything runs ok:</p> <pre><code>stringId = "GRRRRRRRRR" cmd="sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" os.system(cmd) </code></pre> <p>Now, if i try to give a string as a parameter like below, the command is not executed. I do a print to see if the command is correct, and it is. I can even execute it with success if I copy / paste to my shell</p> <pre><code>import os def updateExportConfigId(id): stringId = "%s" % id cmd= "sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" print "command is " + cmd os.system(cmd) </code></pre> <p>Does anyone knows what is wrong?</p> <p>Thanks</p>
2
2009-07-01T12:11:38Z
1,069,233
<p>What is wrong is that there is some difference. Yeah, I know that's not helpful, but you need to figure out the difference.</p> <p>Try running this:</p> <pre><code>import os def updateExportConfigId(id): stringId = "%s" % id cmd1 = "sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" stringId = "GRRRRRRRRR" cmd2 = "sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" print "cmd1:" , cmd1 print "cmd2:" , cmd2 print cmd1 == cmd2 updateExportConfigId("GRRRRRRRRR") </code></pre> <p>The code should print:</p> <pre><code>sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=GRRRRRRRRR/g' path/file.old &gt; path/file.new sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=GRRRRRRRRR/g' path/file.old &gt; path/file.new True </code></pre> <p>Thereby showing that they are exactly the same. If the last line is "False" then they are not the same, and you should be able to see the difference.</p>
1
2009-07-01T13:48:47Z
[ "python" ]
Problem using os.system() with sed command
1,068,812
<p>I'm writing a small method to replace some text in a file. The only argument I need is the new text, as it is always the same file and text to be replaced.</p> <p>I'm having a problem using the os.system() call, when I try to use the argument of the method</p> <p>If I use a string like below, everything runs ok:</p> <pre><code>stringId = "GRRRRRRRRR" cmd="sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" os.system(cmd) </code></pre> <p>Now, if i try to give a string as a parameter like below, the command is not executed. I do a print to see if the command is correct, and it is. I can even execute it with success if I copy / paste to my shell</p> <pre><code>import os def updateExportConfigId(id): stringId = "%s" % id cmd= "sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" print "command is " + cmd os.system(cmd) </code></pre> <p>Does anyone knows what is wrong?</p> <p>Thanks</p>
2
2009-07-01T12:11:38Z
1,069,409
<p>Maybe it helps to use only <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals" rel="nofollow">raw strings</a>.</p>
0
2009-07-01T14:24:43Z
[ "python" ]
Problem using os.system() with sed command
1,068,812
<p>I'm writing a small method to replace some text in a file. The only argument I need is the new text, as it is always the same file and text to be replaced.</p> <p>I'm having a problem using the os.system() call, when I try to use the argument of the method</p> <p>If I use a string like below, everything runs ok:</p> <pre><code>stringId = "GRRRRRRRRR" cmd="sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" os.system(cmd) </code></pre> <p>Now, if i try to give a string as a parameter like below, the command is not executed. I do a print to see if the command is correct, and it is. I can even execute it with success if I copy / paste to my shell</p> <pre><code>import os def updateExportConfigId(id): stringId = "%s" % id cmd= "sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" print "command is " + cmd os.system(cmd) </code></pre> <p>Does anyone knows what is wrong?</p> <p>Thanks</p>
2
2009-07-01T12:11:38Z
1,069,476
<p>So from previous answers we now know that <code>id</code> is a Unicode string, which makes cmd1 a Unicode string, which os.system() is converting to a byte string for execution in the default encoding.</p> <p>a) I suggest using subprocess rather than os.system()</p> <p>b) I suggest not using the name of a built-in function as a variable (<code>id</code>).</p> <p>c) I suggest explicitly encoding the string to a byte string before executing:</p> <pre><code>if isinstance(cmd,unicode): cmd = cmd.encode("UTF-8") </code></pre> <p>d) For Lennart Regebro's suggestion add:</p> <pre><code>assert type(cmd1) == type(cmd2) </code></pre> <p>after</p> <pre><code>print cmd1 == cmd2 </code></pre>
1
2009-07-01T14:34:59Z
[ "python" ]
Problem using os.system() with sed command
1,068,812
<p>I'm writing a small method to replace some text in a file. The only argument I need is the new text, as it is always the same file and text to be replaced.</p> <p>I'm having a problem using the os.system() call, when I try to use the argument of the method</p> <p>If I use a string like below, everything runs ok:</p> <pre><code>stringId = "GRRRRRRRRR" cmd="sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" os.system(cmd) </code></pre> <p>Now, if i try to give a string as a parameter like below, the command is not executed. I do a print to see if the command is correct, and it is. I can even execute it with success if I copy / paste to my shell</p> <pre><code>import os def updateExportConfigId(id): stringId = "%s" % id cmd= "sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" print "command is " + cmd os.system(cmd) </code></pre> <p>Does anyone knows what is wrong?</p> <p>Thanks</p>
2
2009-07-01T12:11:38Z
1,069,587
<p>Finally, I found a way to run the os.system(cmd)!</p> <p>Simple trick, to "clean" the cmd string:</p> <pre><code>os.system(str(cmd)) </code></pre> <p>Now, I'm able to build the cmd with all arguments I need and at the end I just "clean" it with str() call before run it with os.system() call.</p> <p>Thanks a lot for your answers!</p> <p>swon</p>
0
2009-07-01T14:52:34Z
[ "python" ]
Problem using os.system() with sed command
1,068,812
<p>I'm writing a small method to replace some text in a file. The only argument I need is the new text, as it is always the same file and text to be replaced.</p> <p>I'm having a problem using the os.system() call, when I try to use the argument of the method</p> <p>If I use a string like below, everything runs ok:</p> <pre><code>stringId = "GRRRRRRRRR" cmd="sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" os.system(cmd) </code></pre> <p>Now, if i try to give a string as a parameter like below, the command is not executed. I do a print to see if the command is correct, and it is. I can even execute it with success if I copy / paste to my shell</p> <pre><code>import os def updateExportConfigId(id): stringId = "%s" % id cmd= "sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old &gt; path/file.new" print "command is " + cmd os.system(cmd) </code></pre> <p>Does anyone knows what is wrong?</p> <p>Thanks</p>
2
2009-07-01T12:11:38Z
1,072,091
<p>Obligatory: <strong>don't use <code>os.system</code></strong> - use the <a href="http://docs.python.org/library/subprocess.html"><code>subprocess</code></a> module:</p> <pre><code>import subprocess def updateExportConfigId(m_id, source='path/file.old', destination='path/file.new'): if isinstance(m_id, unicode): m_id = m_id.encode('utf-8') cmd= [ "sed", ",$s/MANAGER_ID=[0-9]*/MANAGER_ID=%s/g" % m_id, source, ] subprocess.call(cmd, stdout=open(destination, 'w')) </code></pre> <p>with this code you can pass the manager id, it can have spaces, quote chars, etc. The file names can also be passed to the function, and can also contain spaces and some other special chars. That's because your shell is not unnecessarly invoked, so one less process is started on your OS, and you don't have to worry on escaping special shell characters.</p> <p>Another option: Don't launch sed. Use python's <a href="http://docs.python.org/library/re.html"><code>re</code></a> module. </p> <pre><code>import re def updateExportConfigID(m_id, source, destination): if isinstance(m_id, unicode): m_id = m_id.encode('utf-8') for line in source: new_line = re.sub(r'MANAGER_ID=\d*', r'MANAGER_ID=' + re.escape(m_id), line) destination.write(new_line) </code></pre> <p>and call it like this:</p> <pre><code>updateExportConfigID('GRRRR', open('path/file.old'), open('path/file.new', 'w')) </code></pre> <p>No new processes needed.</p>
5
2009-07-02T02:07:20Z
[ "python" ]
Open-Source Forum with API
1,069,246
<p>Does anyone have suggestions for a PHP, Python, or J2EE-based web forum that has a good API for programmatically creating users and forum topics?</p>
6
2009-07-01T13:51:38Z
1,069,283
<p><a href="http://www.phpbb.com/" rel="nofollow">phpBB</a> would be the first that comes to mind as open-source, simply because it's free. </p> <p>In reality almost all forum platforms have some sort of 'api' in that you can do whatever you need programatically, it just may not be as simple as 'add_user(bob)'. A few lines of code and a SQL query or two and you can usually achieve everything you need.</p> <p>Out of personal preference I would recommend vBulletin, however it does have a fee. The benefit of this is that it has a very strong modding community that have probably already accomplished everything you need at <a href="http://vbulletin.org" rel="nofollow">http://vbulletin.org</a>.</p>
3
2009-07-01T14:02:49Z
[ "php", "python", "website", "forum" ]
using profiles in iPython and Django
1,069,961
<p>I've got a Django product I'm using iPython to interact with.</p> <p>I'm trying to have modules automatically loaded when I start a shell:</p> <p>python manage.py shell</p> <p>I've copied .ipython/ipythonrc to the root directory of the project and added to the file:</p> <p>import_some module_name model1 model2</p> <p>However, when I start the shell, these names are not being loaded.</p> <p>What am I doing wrong?</p>
3
2009-07-01T15:55:13Z
1,070,222
<p>I don't know about ipythonrc, but if you only need the models, you could use <a href="http://code.google.com/p/django-command-extensions/" rel="nofollow"><code>django-extensions</code></a>. After you install it, you've got a plethora of new managment commands, including <code>shell_plus</code>, which will open a ipython session and autoload all your models:</p> <pre><code>python manage.py shell_plus </code></pre>
5
2009-07-01T16:53:19Z
[ "python", "django", "ipython" ]
using profiles in iPython and Django
1,069,961
<p>I've got a Django product I'm using iPython to interact with.</p> <p>I'm trying to have modules automatically loaded when I start a shell:</p> <p>python manage.py shell</p> <p>I've copied .ipython/ipythonrc to the root directory of the project and added to the file:</p> <p>import_some module_name model1 model2</p> <p>However, when I start the shell, these names are not being loaded.</p> <p>What am I doing wrong?</p>
3
2009-07-01T15:55:13Z
1,303,140
<p>BryanWheelock Your solution won't work because your shell is the result of the spawn not a direct interatction with it. What you want to do is this - or at least this is what I do.</p> <p>Within your workspace (the place where you type <code>python manage.py shell</code>) create a ipythonrc file. In it put the following:</p> <pre><code>include ~/.ipython/ipythonrc execute from django.contrib.auth.models import User # . # . # . execute import_some module_name model1 model2 </code></pre> <p>For example I also add the following lines in mine..</p> <pre><code># Setup Logging execute import sys execute import logging execute loglevel = logging.DEBUG execute logging.basicConfig(format="%(levelname)-8s %(asctime)s %(name)s %(message)s", datefmt='%m/%d/%y %H:%M:%S', stream=sys.stdout ) execute log = logging.getLogger("") execute log.setLevel(loglevel) execute log.debug("Logging has been initialized from ipythonrc") execute log.debug("Root Logger has been established - use \"log.LEVEL(MSG)\"") execute log.setLevel(loglevel) execute log.debug("log.setlevel(logging.DEBUG)") execute print "" </code></pre> <p>This allows you to use logging in your modules and keep it DRY. Hope this helps.</p>
1
2009-08-19T23:19:52Z
[ "python", "django", "ipython" ]
using profiles in iPython and Django
1,069,961
<p>I've got a Django product I'm using iPython to interact with.</p> <p>I'm trying to have modules automatically loaded when I start a shell:</p> <p>python manage.py shell</p> <p>I've copied .ipython/ipythonrc to the root directory of the project and added to the file:</p> <p>import_some module_name model1 model2</p> <p>However, when I start the shell, these names are not being loaded.</p> <p>What am I doing wrong?</p>
3
2009-07-01T15:55:13Z
29,457,821
<p><code>shell_plus</code> command of django-extensions can import the model automatically, but it seems can not load the profile of ipython. I have did some hacky job to make this done. </p> <p>use <code>start_ipython</code> to launch ipython shell instead of <code>embed</code> and pass some arguments to it.</p> <p>I have also wrote a blog post, you can find the detail <a href="http://blog.michaelyin.info/2015/04/05/using-profiles-in-ipython-and-django/" rel="nofollow">here</a></p>
0
2015-04-05T13:32:35Z
[ "python", "django", "ipython" ]
Python + CGI script cannot access environment variables
1,070,525
<p>I'm coding a webservice on python that uses an Oracle database. I have cx_Oracle installed and working but I'm having some problems when I run my python code as CGI using Apache.</p> <p>For example the following code works perfectly at the command line:</p> <pre><code>#!/usr/bin/python import os import cx_Oracle import defs as df os.putenv('ORACLE_HOME', '/oracledb/10.2.0/') os.putenv('LD_LIBRARY_PATH', '/oracledb/10.2.0/lib') con = cx_Oracle.Connection(df.DB_USER, df.DB_PASS, df.DB_SID) print con </code></pre> <p>But when I run it as CGI I get a "cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle" at the apache error log.</p> <p>I searched the Net and everybody says that I have to set the <code>ORACLE_HOME</code> and <code>LD_LIBRARY_PATH</code> environment variables. Somehow the CGI script cannot access this environment variables even when I define them using <code>os.putenv</code> as you can see at the code.</p> <p>What I'm I doing wrong? Thanks!</p>
5
2009-07-01T18:03:47Z
1,070,543
<p>You need this:</p> <pre><code>os.environ['ORACLE_HOME'] = '/oracledb/10.2.0/' os.environ['LD_LIBRARY_PATH'] = '/oracledb/10.2.0/lib' </code></pre> <p>instead of using <code>os.putenv()</code> because <code>os.putenv()</code> doesn't update <code>os.environ</code>, which <code>cx_Oracle</code> is presumably looking at.</p> <p>Documentation: <a href="http://docs.python.org/library/os.html" rel="nofollow">Miscellaneous operating system interfaces</a> says: <em>"Note: Calling putenv() directly does not change os.environ, so it’s better to modify os.environ."</em></p>
3
2009-07-01T18:06:19Z
[ "python", "apache", "cgi", "cx-oracle" ]
Python + CGI script cannot access environment variables
1,070,525
<p>I'm coding a webservice on python that uses an Oracle database. I have cx_Oracle installed and working but I'm having some problems when I run my python code as CGI using Apache.</p> <p>For example the following code works perfectly at the command line:</p> <pre><code>#!/usr/bin/python import os import cx_Oracle import defs as df os.putenv('ORACLE_HOME', '/oracledb/10.2.0/') os.putenv('LD_LIBRARY_PATH', '/oracledb/10.2.0/lib') con = cx_Oracle.Connection(df.DB_USER, df.DB_PASS, df.DB_SID) print con </code></pre> <p>But when I run it as CGI I get a "cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle" at the apache error log.</p> <p>I searched the Net and everybody says that I have to set the <code>ORACLE_HOME</code> and <code>LD_LIBRARY_PATH</code> environment variables. Somehow the CGI script cannot access this environment variables even when I define them using <code>os.putenv</code> as you can see at the code.</p> <p>What I'm I doing wrong? Thanks!</p>
5
2009-07-01T18:03:47Z
1,070,555
<p>Are your statements out of order?</p> <pre><code>#!/usr/bin/python import os os.putenv('ORACLE_HOME', '/oracledb/10.2.0/') os.putenv('LD_LIBRARY_PATH', '/oracledb/10.2.0/lib') import cx_Oracle import defs as df con = cx_Oracle.Connection(df.DB_USER, df.DB_PASS, df.DB_SID) print con </code></pre>
0
2009-07-01T18:07:35Z
[ "python", "apache", "cgi", "cx-oracle" ]
Python + CGI script cannot access environment variables
1,070,525
<p>I'm coding a webservice on python that uses an Oracle database. I have cx_Oracle installed and working but I'm having some problems when I run my python code as CGI using Apache.</p> <p>For example the following code works perfectly at the command line:</p> <pre><code>#!/usr/bin/python import os import cx_Oracle import defs as df os.putenv('ORACLE_HOME', '/oracledb/10.2.0/') os.putenv('LD_LIBRARY_PATH', '/oracledb/10.2.0/lib') con = cx_Oracle.Connection(df.DB_USER, df.DB_PASS, df.DB_SID) print con </code></pre> <p>But when I run it as CGI I get a "cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle" at the apache error log.</p> <p>I searched the Net and everybody says that I have to set the <code>ORACLE_HOME</code> and <code>LD_LIBRARY_PATH</code> environment variables. Somehow the CGI script cannot access this environment variables even when I define them using <code>os.putenv</code> as you can see at the code.</p> <p>What I'm I doing wrong? Thanks!</p>
5
2009-07-01T18:03:47Z
1,070,647
<p>From just a short <a href="http://osdir.com/ml/python.db.cx-oracle/2006-01/msg00007.html" rel="nofollow">google</a> on the problem, it could be that your problem is related to the the ending <code>/</code> in <code>ORACLE_HOME</code>.<br /> Try removing it (and using also suggestion from Richie) and see if it works.</p>
1
2009-07-01T18:32:57Z
[ "python", "apache", "cgi", "cx-oracle" ]
Python + CGI script cannot access environment variables
1,070,525
<p>I'm coding a webservice on python that uses an Oracle database. I have cx_Oracle installed and working but I'm having some problems when I run my python code as CGI using Apache.</p> <p>For example the following code works perfectly at the command line:</p> <pre><code>#!/usr/bin/python import os import cx_Oracle import defs as df os.putenv('ORACLE_HOME', '/oracledb/10.2.0/') os.putenv('LD_LIBRARY_PATH', '/oracledb/10.2.0/lib') con = cx_Oracle.Connection(df.DB_USER, df.DB_PASS, df.DB_SID) print con </code></pre> <p>But when I run it as CGI I get a "cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle" at the apache error log.</p> <p>I searched the Net and everybody says that I have to set the <code>ORACLE_HOME</code> and <code>LD_LIBRARY_PATH</code> environment variables. Somehow the CGI script cannot access this environment variables even when I define them using <code>os.putenv</code> as you can see at the code.</p> <p>What I'm I doing wrong? Thanks!</p>
5
2009-07-01T18:03:47Z
1,070,694
<p>You could use a shell script to implement the CGI, set the environment variables in the shell script and call the python script from the shell script.</p> <p>Setting environment variables from within python seems to be a tricky thing, especially when you are dealing with how libraries are loaded...</p>
1
2009-07-01T18:42:52Z
[ "python", "apache", "cgi", "cx-oracle" ]
Python + CGI script cannot access environment variables
1,070,525
<p>I'm coding a webservice on python that uses an Oracle database. I have cx_Oracle installed and working but I'm having some problems when I run my python code as CGI using Apache.</p> <p>For example the following code works perfectly at the command line:</p> <pre><code>#!/usr/bin/python import os import cx_Oracle import defs as df os.putenv('ORACLE_HOME', '/oracledb/10.2.0/') os.putenv('LD_LIBRARY_PATH', '/oracledb/10.2.0/lib') con = cx_Oracle.Connection(df.DB_USER, df.DB_PASS, df.DB_SID) print con </code></pre> <p>But when I run it as CGI I get a "cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle" at the apache error log.</p> <p>I searched the Net and everybody says that I have to set the <code>ORACLE_HOME</code> and <code>LD_LIBRARY_PATH</code> environment variables. Somehow the CGI script cannot access this environment variables even when I define them using <code>os.putenv</code> as you can see at the code.</p> <p>What I'm I doing wrong? Thanks!</p>
5
2009-07-01T18:03:47Z
1,078,124
<p>You can eliminate the problem altogether if you eliminate the need to set the environment variables. Here's a note on how to do this by installing the Oracle Instant Client on your box.</p> <p><a href="http://stackoverflow.com/questions/764871/installing-oracle-instantclient-on-linux-without-setting-environment-variables">http://stackoverflow.com/questions/764871/installing-oracle-instantclient-on-linux-without-setting-environment-variables</a></p>
2
2009-07-03T07:10:02Z
[ "python", "apache", "cgi", "cx-oracle" ]
Python + CGI script cannot access environment variables
1,070,525
<p>I'm coding a webservice on python that uses an Oracle database. I have cx_Oracle installed and working but I'm having some problems when I run my python code as CGI using Apache.</p> <p>For example the following code works perfectly at the command line:</p> <pre><code>#!/usr/bin/python import os import cx_Oracle import defs as df os.putenv('ORACLE_HOME', '/oracledb/10.2.0/') os.putenv('LD_LIBRARY_PATH', '/oracledb/10.2.0/lib') con = cx_Oracle.Connection(df.DB_USER, df.DB_PASS, df.DB_SID) print con </code></pre> <p>But when I run it as CGI I get a "cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle" at the apache error log.</p> <p>I searched the Net and everybody says that I have to set the <code>ORACLE_HOME</code> and <code>LD_LIBRARY_PATH</code> environment variables. Somehow the CGI script cannot access this environment variables even when I define them using <code>os.putenv</code> as you can see at the code.</p> <p>What I'm I doing wrong? Thanks!</p>
5
2009-07-01T18:03:47Z
1,143,584
<p>I've managed to solve the problem.</p> <p>Somehow the user and group that apache was using didn't have access to the environment variables. I solved the problem by changing the user and group that apache was using to a user that I was certain to have access to this variables. </p> <p>It's strange (and frustrating) that it's so difficult to set this variables using Python.</p> <p>Thanks to everyone that answered my question!</p>
1
2009-07-17T14:17:25Z
[ "python", "apache", "cgi", "cx-oracle" ]
Python + CGI script cannot access environment variables
1,070,525
<p>I'm coding a webservice on python that uses an Oracle database. I have cx_Oracle installed and working but I'm having some problems when I run my python code as CGI using Apache.</p> <p>For example the following code works perfectly at the command line:</p> <pre><code>#!/usr/bin/python import os import cx_Oracle import defs as df os.putenv('ORACLE_HOME', '/oracledb/10.2.0/') os.putenv('LD_LIBRARY_PATH', '/oracledb/10.2.0/lib') con = cx_Oracle.Connection(df.DB_USER, df.DB_PASS, df.DB_SID) print con </code></pre> <p>But when I run it as CGI I get a "cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle" at the apache error log.</p> <p>I searched the Net and everybody says that I have to set the <code>ORACLE_HOME</code> and <code>LD_LIBRARY_PATH</code> environment variables. Somehow the CGI script cannot access this environment variables even when I define them using <code>os.putenv</code> as you can see at the code.</p> <p>What I'm I doing wrong? Thanks!</p>
5
2009-07-01T18:03:47Z
5,394,590
<p>This is working for me:</p> <pre><code>os.putenv('ORACLE_HOME', '/oracle/client/v10.2.0.3-64bit') os.putenv('LD_LIBRARY_PATH', '/oracle/client/v10.2.0.3-64bit/lib') os.environ['ORACLE_HOME'] = '/oracle/client/v10.2.0.3-64bit' os.environ['LD_LIBRARY_PATH'] = '/oracle/client/v10.2.0.3-64bit/lib' </code></pre> <p>Mind that first <code>putenv</code>, then update <code>environ</code>.</p>
5
2011-03-22T16:31:57Z
[ "python", "apache", "cgi", "cx-oracle" ]
Python + CGI script cannot access environment variables
1,070,525
<p>I'm coding a webservice on python that uses an Oracle database. I have cx_Oracle installed and working but I'm having some problems when I run my python code as CGI using Apache.</p> <p>For example the following code works perfectly at the command line:</p> <pre><code>#!/usr/bin/python import os import cx_Oracle import defs as df os.putenv('ORACLE_HOME', '/oracledb/10.2.0/') os.putenv('LD_LIBRARY_PATH', '/oracledb/10.2.0/lib') con = cx_Oracle.Connection(df.DB_USER, df.DB_PASS, df.DB_SID) print con </code></pre> <p>But when I run it as CGI I get a "cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle" at the apache error log.</p> <p>I searched the Net and everybody says that I have to set the <code>ORACLE_HOME</code> and <code>LD_LIBRARY_PATH</code> environment variables. Somehow the CGI script cannot access this environment variables even when I define them using <code>os.putenv</code> as you can see at the code.</p> <p>What I'm I doing wrong? Thanks!</p>
5
2009-07-01T18:03:47Z
8,331,159
<p>The actual question why the questioner's code did not work has not yet been answered.</p> <p>The answer is that the environment variable LD_LIBRARY_PATH is only evaluated when an application is started (in this case the Python interpreter). When Python has started, it is already too late to mess with this variable; and it doesn't matter at all whether you set it using os.environ or os.putenv (but generally the former should be used).</p> <p>The solution is to set the LD_LIBRARY_PATH environment variable in a wrapper script that starts the Python script, or to start Apache with that environment variable already set. On OpenSUSE, you can do the latter by setting LD_LIBRARY_PATH in /etc/sysconfig/apache2, for instance.</p> <p>By the way, the same problem exists when using mod_wsgi instead of a CGI script. See the section "Unable To Find Python Shared Library" on the mod_wsgi <a href="http://code.google.com/p/modwsgi/wiki/InstallationIssues" rel="nofollow">Installation Issues</a> page.</p>
0
2011-11-30T18:42:25Z
[ "python", "apache", "cgi", "cx-oracle" ]
Python + CGI script cannot access environment variables
1,070,525
<p>I'm coding a webservice on python that uses an Oracle database. I have cx_Oracle installed and working but I'm having some problems when I run my python code as CGI using Apache.</p> <p>For example the following code works perfectly at the command line:</p> <pre><code>#!/usr/bin/python import os import cx_Oracle import defs as df os.putenv('ORACLE_HOME', '/oracledb/10.2.0/') os.putenv('LD_LIBRARY_PATH', '/oracledb/10.2.0/lib') con = cx_Oracle.Connection(df.DB_USER, df.DB_PASS, df.DB_SID) print con </code></pre> <p>But when I run it as CGI I get a "cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle" at the apache error log.</p> <p>I searched the Net and everybody says that I have to set the <code>ORACLE_HOME</code> and <code>LD_LIBRARY_PATH</code> environment variables. Somehow the CGI script cannot access this environment variables even when I define them using <code>os.putenv</code> as you can see at the code.</p> <p>What I'm I doing wrong? Thanks!</p>
5
2009-07-01T18:03:47Z
8,986,919
<p>Don't forget adding <strong>env</strong> module for apache:</p> <pre><code>a2enmod env </code></pre> <p>in .htaccess or apache configuration:</p> <pre><code>SetEnv LD_LIBRARY_PATH /oracle_lib_path </code></pre> <p>in /etc/apache2/envvars doesn't work</p>
2
2012-01-24T12:37:19Z
[ "python", "apache", "cgi", "cx-oracle" ]
How to create "virtual root" with Python's ElementTree?
1,070,772
<p>I am trying to use Python's ElementTree to generate an XHTML file.</p> <p>However, the ElementTree.Element() just lets me create a single tag (e.g., HTML). I need to create some sort of a virtual root or whatever it is called so that I can put the various , DOCTYPES, etc.</p> <p>How do I do that? Thanks</p>
5
2009-07-01T19:02:08Z
1,070,796
<p>I don't know if there's a better way but I've seen this done:</p> <p>Create the base document as a string:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html&gt;&lt;/html&gt; </code></pre> <p>Then parse that string to start your new document.</p>
7
2009-07-01T19:07:24Z
[ "python", "elementtree" ]
How to create "virtual root" with Python's ElementTree?
1,070,772
<p>I am trying to use Python's ElementTree to generate an XHTML file.</p> <p>However, the ElementTree.Element() just lets me create a single tag (e.g., HTML). I need to create some sort of a virtual root or whatever it is called so that I can put the various , DOCTYPES, etc.</p> <p>How do I do that? Thanks</p>
5
2009-07-01T19:02:08Z
2,177,037
<p>I have/had the same problem. when i parse a document and write it back again the doctype defenition is not there anymore. but i found a solution browsing the documentation:</p> <p><a href="http://effbot.org/zone/element-tidylib.htm" rel="nofollow">link text</a></p> <p>Saving HTML Files #</p> <p>To save a plain HTML file, just write out the tree.</p> <pre><code>tree.write("outfile.htm") </code></pre> <p>This works well, as long as the file doesn’t containg any embedded SCRIPT or STYLE tags.</p> <p>If you want, you can add a DTD reference to the beginning of the file:</p> <pre><code>file = open("outfile.htm", "w") file.write(DTD + "\n") tree.write(file) file.close() </code></pre>
0
2010-02-01T13:45:18Z
[ "python", "elementtree" ]
Equivalent for inject() in Python?
1,070,926
<p>In Ruby, I'm used to using Enumerable#inject for going through a list or other structure and coming back with some conclusion about it. For example,</p> <pre><code>[1,3,5,7].inject(true) {|allOdd, n| allOdd &amp;&amp; n % 2 == 1} </code></pre> <p>to determine if every element in the array is odd. What would be the appropriate way to accomplish the same thing in Python?</p>
8
2009-07-01T19:36:42Z
1,070,946
<p>Sounds like <code>reduce</code> in Python or <code>fold(r|l)'?'</code> from Haskell.</p> <pre><code>reduce(lambda x, y: x and y % == 1, [1, 3, 5]) </code></pre>
4
2009-07-01T19:41:04Z
[ "python", "functional-programming" ]
Equivalent for inject() in Python?
1,070,926
<p>In Ruby, I'm used to using Enumerable#inject for going through a list or other structure and coming back with some conclusion about it. For example,</p> <pre><code>[1,3,5,7].inject(true) {|allOdd, n| allOdd &amp;&amp; n % 2 == 1} </code></pre> <p>to determine if every element in the array is odd. What would be the appropriate way to accomplish the same thing in Python?</p>
8
2009-07-01T19:36:42Z
1,070,965
<p>To determine if every element is odd, I'd use <a href="http://docs.python.org/library/functions.html#all"><code>all()</code></a></p> <pre><code>def is_odd(x): return x%2==1 result = all(is_odd(x) for x in [1,3,5,7]) </code></pre> <p>In general, however, Ruby's <code>inject</code> is most like Python's <a href="http://docs.python.org/library/functions.html#reduce"><code>reduce()</code></a>:</p> <pre><code>result = reduce(lambda x,y: x and y%2==1, [1,3,5,7], True) </code></pre> <p><code>all()</code> is preferred in this case because it will be able to escape the loop once it finds a <code>False</code>-like value, whereas the <code>reduce</code> solution would have to process the entire list to return an answer.</p>
19
2009-07-01T19:45:01Z
[ "python", "functional-programming" ]
Equivalent for inject() in Python?
1,070,926
<p>In Ruby, I'm used to using Enumerable#inject for going through a list or other structure and coming back with some conclusion about it. For example,</p> <pre><code>[1,3,5,7].inject(true) {|allOdd, n| allOdd &amp;&amp; n % 2 == 1} </code></pre> <p>to determine if every element in the array is odd. What would be the appropriate way to accomplish the same thing in Python?</p>
8
2009-07-01T19:36:42Z
1,071,028
<p>I think you probably want to use <code>all</code>, which is less general than <code>inject</code>. <code>reduce</code> is the Python equivalent of <code>inject</code>, though.</p> <pre><code>all(n % 2 == 1 for n in [1, 3, 5, 7]) </code></pre>
3
2009-07-01T19:57:41Z
[ "python", "functional-programming" ]
How To: View MFC Doc File in Python
1,070,932
<p>I want to use Python to access MFC document files generically? Can CArchive be used to query a file and view the structure, or does Python, in opening the document, need to know more about the document structure in order to view the contents?</p>
1
2009-07-01T19:37:12Z
1,071,011
<p>I think that the Python code needs to know the document structure. </p> <p>Maybe you should make a python wrapper of your c++ code. </p> <p>In this case, I would recommend to use http://sourceforge.net/projects/pycpp/>pycpp which is my opinion a great library for making python extensions in c++.</p>
0
2009-07-01T19:53:10Z
[ "python", "windows", "mfc", "file" ]
Writing a website in Python
1,070,999
<p>I'm pretty proficient in PHP, but want to try something new.</p> <p>I'm also know a bit of Python, enough to do the basics of the basics, but haven't used in a web design type situation.</p> <p>I've just written this, which works:</p> <pre><code>#!/usr/bin/python def main(): print "Content-type: text/html" print print "&lt;html&gt;&lt;head&gt;" print "&lt;title&gt;Hello World from Python&lt;/title&gt;" print "&lt;/head&gt;&lt;body&gt;" print "Hello World!" print "&lt;/body&gt;&lt;/html&gt;" if __name__ == "__main__": main() </code></pre> <p>Thing is, that this seems pretty cumbersome. Without using something huge like django, what's the best way to write scripts that can process get and post?</p>
19
2009-07-01T19:50:19Z
1,071,015
<p>As far as full frameworks go I believe Django is relatively small.</p> <p>If you <em>really</em> want lightweight, though, check out <a href="http://webpy.org/">web.py</a>, <a href="http://www.cherrypy.org/">CherryPy</a>, <a href="http://pylonshq.com/">Pylons</a> and <a href="http://www.web2py.com/">web2py</a>.</p> <p>I think the crowd favorite from the above is Pylons, but I am a Django man so I can't say much else.</p> <p>For more on lightweight Python frameworks, check out <a href="http://stackoverflow.com/questions/68986/whats-a-good-lightweight-python-mvc-framework">this question</a>.</p>
11
2009-07-01T19:54:00Z
[ "python" ]
Writing a website in Python
1,070,999
<p>I'm pretty proficient in PHP, but want to try something new.</p> <p>I'm also know a bit of Python, enough to do the basics of the basics, but haven't used in a web design type situation.</p> <p>I've just written this, which works:</p> <pre><code>#!/usr/bin/python def main(): print "Content-type: text/html" print print "&lt;html&gt;&lt;head&gt;" print "&lt;title&gt;Hello World from Python&lt;/title&gt;" print "&lt;/head&gt;&lt;body&gt;" print "Hello World!" print "&lt;/body&gt;&lt;/html&gt;" if __name__ == "__main__": main() </code></pre> <p>Thing is, that this seems pretty cumbersome. Without using something huge like django, what's the best way to write scripts that can process get and post?</p>
19
2009-07-01T19:50:19Z
1,071,040
<p>There are a couple of web frameworks available in python, that will relieve you from most of the work</p> <ol> <li><a href="http://docs.djangoproject.com/en/dev/" rel="nofollow">Django</a></li> <li><a href="http://pylonshq.com/" rel="nofollow">Pylons</a> (and the new TurboGears, based on it).</li> <li><a href="http://www.web2py.com/" rel="nofollow">Web2py</a></li> <li><a href="http://www.cherrypy.org/" rel="nofollow">CherryPy</a> (and the old TurboGears, based on it)</li> </ol> <p>I do not feel Django as "big" as you say; however, I think that Pylons and CherryPy may be a better answer to your question. CherryPy seems simpler,. but seems also a bit "passé", while Pylons is under active development.<br /> For Pylons, there is also an interesting <a href="http://pylonsbook.com/en/1.0/index.html" rel="nofollow">Pylons book</a>, available online.</p>
8
2009-07-01T19:59:03Z
[ "python" ]
Writing a website in Python
1,070,999
<p>I'm pretty proficient in PHP, but want to try something new.</p> <p>I'm also know a bit of Python, enough to do the basics of the basics, but haven't used in a web design type situation.</p> <p>I've just written this, which works:</p> <pre><code>#!/usr/bin/python def main(): print "Content-type: text/html" print print "&lt;html&gt;&lt;head&gt;" print "&lt;title&gt;Hello World from Python&lt;/title&gt;" print "&lt;/head&gt;&lt;body&gt;" print "Hello World!" print "&lt;/body&gt;&lt;/html&gt;" if __name__ == "__main__": main() </code></pre> <p>Thing is, that this seems pretty cumbersome. Without using something huge like django, what's the best way to write scripts that can process get and post?</p>
19
2009-07-01T19:50:19Z
1,071,048
<p>I really love django and it doesn't seem to me that is huge. It is very powerful but not huge.</p> <p>If you want to start playing with http and python, the simplest thing is the BaseHttpServer provided in the standard library. see <a href="http://docs.python.org/library/basehttpserver.html" rel="nofollow">http://docs.python.org/library/basehttpserver.html</a> for details</p>
0
2009-07-01T20:00:28Z
[ "python" ]
Writing a website in Python
1,070,999
<p>I'm pretty proficient in PHP, but want to try something new.</p> <p>I'm also know a bit of Python, enough to do the basics of the basics, but haven't used in a web design type situation.</p> <p>I've just written this, which works:</p> <pre><code>#!/usr/bin/python def main(): print "Content-type: text/html" print print "&lt;html&gt;&lt;head&gt;" print "&lt;title&gt;Hello World from Python&lt;/title&gt;" print "&lt;/head&gt;&lt;body&gt;" print "Hello World!" print "&lt;/body&gt;&lt;/html&gt;" if __name__ == "__main__": main() </code></pre> <p>Thing is, that this seems pretty cumbersome. Without using something huge like django, what's the best way to write scripts that can process get and post?</p>
19
2009-07-01T19:50:19Z
1,071,058
<p>I agree with Paolo - Django is pretty small and the way to go - but if you are not down with that I would add to <a href="http://turbogears.org/" rel="nofollow">TurboGears</a> to the list</p>
0
2009-07-01T20:01:24Z
[ "python" ]
Writing a website in Python
1,070,999
<p>I'm pretty proficient in PHP, but want to try something new.</p> <p>I'm also know a bit of Python, enough to do the basics of the basics, but haven't used in a web design type situation.</p> <p>I've just written this, which works:</p> <pre><code>#!/usr/bin/python def main(): print "Content-type: text/html" print print "&lt;html&gt;&lt;head&gt;" print "&lt;title&gt;Hello World from Python&lt;/title&gt;" print "&lt;/head&gt;&lt;body&gt;" print "Hello World!" print "&lt;/body&gt;&lt;/html&gt;" if __name__ == "__main__": main() </code></pre> <p>Thing is, that this seems pretty cumbersome. Without using something huge like django, what's the best way to write scripts that can process get and post?</p>
19
2009-07-01T19:50:19Z
1,071,128
<p>If you are looking for a framework take a look at this list: <a href="http://wiki.python.org/moin/WebFrameworks" rel="nofollow">Python Web Frameworks</a></p> <p>If you need small script(-s) or one time job script, might be plain CGI module is going to be enough - <a href="http://wiki.python.org/moin/CgiScripts" rel="nofollow">CGI Scripts</a> and <a href="http://docs.python.org/library/cgi.html" rel="nofollow">cgi module</a> itself.</p> <p>I would recommend you to stick to some framework if you want to create something more then static pages and simple forms. Django is I believe most popular and most supported.</p>
0
2009-07-01T20:14:25Z
[ "python" ]
Writing a website in Python
1,070,999
<p>I'm pretty proficient in PHP, but want to try something new.</p> <p>I'm also know a bit of Python, enough to do the basics of the basics, but haven't used in a web design type situation.</p> <p>I've just written this, which works:</p> <pre><code>#!/usr/bin/python def main(): print "Content-type: text/html" print print "&lt;html&gt;&lt;head&gt;" print "&lt;title&gt;Hello World from Python&lt;/title&gt;" print "&lt;/head&gt;&lt;body&gt;" print "Hello World!" print "&lt;/body&gt;&lt;/html&gt;" if __name__ == "__main__": main() </code></pre> <p>Thing is, that this seems pretty cumbersome. Without using something huge like django, what's the best way to write scripts that can process get and post?</p>
19
2009-07-01T19:50:19Z
1,071,129
<p>Your question was about basic CGI scripting, looking at your example, but it seems like everyone has chosen to answer it with "use my favorite framework". Let's try a different approach.</p> <p>If you're looking for a direct replacement for what you wrote above (ie. CGI scripting), then you're probably looking for the <a href="http://docs.python.org/library/cgi.html">cgi</a> module. It's a part of the Python standard library. Complimentary functionality is available in <a href="http://docs.python.org/library/urllib.html">urllib</a> and <a href="http://docs.python.org/library/urllib2.html">urllib2</a>. You might also be interested in <a href="http://docs.python.org/library/basehttpserver.html">BaseHTTPServer</a> and <a href="http://docs.python.org/library/simplehttpserver.html">SimpleHTTPServer</a>, also part of the standard library.</p> <p>Getting into more interesting territory, <a href="http://docs.python.org/library/wsgiref.html">wsgiref</a> gives you the basics of a <a href="http://www.wsgi.org/wsgi/">WSGI</a> interface, at which point you probably want to start thinking about more "frameworky" (is that a word?) things like web.py, Django, Pylons, CherryPy, etc, as others have mentioned.</p>
24
2009-07-01T20:14:25Z
[ "python" ]
Writing a website in Python
1,070,999
<p>I'm pretty proficient in PHP, but want to try something new.</p> <p>I'm also know a bit of Python, enough to do the basics of the basics, but haven't used in a web design type situation.</p> <p>I've just written this, which works:</p> <pre><code>#!/usr/bin/python def main(): print "Content-type: text/html" print print "&lt;html&gt;&lt;head&gt;" print "&lt;title&gt;Hello World from Python&lt;/title&gt;" print "&lt;/head&gt;&lt;body&gt;" print "Hello World!" print "&lt;/body&gt;&lt;/html&gt;" if __name__ == "__main__": main() </code></pre> <p>Thing is, that this seems pretty cumbersome. Without using something huge like django, what's the best way to write scripts that can process get and post?</p>
19
2009-07-01T19:50:19Z
1,071,255
<p>What is "huge" is a matter of taste, but Django is a "full stack" framework, that includes everything from an ORM, to templates to well, loads of things. So it's not small (although smaller than Grok and Zope3, other full-stack python web frameworks).</p> <p>But there are also plenty of really small and minimalistic web frameworks, that do nothing than provide a framework for the web part. Many have been mentioned above. To the list I must add BFG and Bobo. Both utterly minimal, but still useful and flexible.</p> <p><a href="http://bfg.repoze.org/" rel="nofollow">http://bfg.repoze.org/</a> <a href="http://bobo.digicool.com/" rel="nofollow">http://bobo.digicool.com/</a></p>
0
2009-07-01T20:34:22Z
[ "python" ]
Writing a website in Python
1,070,999
<p>I'm pretty proficient in PHP, but want to try something new.</p> <p>I'm also know a bit of Python, enough to do the basics of the basics, but haven't used in a web design type situation.</p> <p>I've just written this, which works:</p> <pre><code>#!/usr/bin/python def main(): print "Content-type: text/html" print print "&lt;html&gt;&lt;head&gt;" print "&lt;title&gt;Hello World from Python&lt;/title&gt;" print "&lt;/head&gt;&lt;body&gt;" print "Hello World!" print "&lt;/body&gt;&lt;/html&gt;" if __name__ == "__main__": main() </code></pre> <p>Thing is, that this seems pretty cumbersome. Without using something huge like django, what's the best way to write scripts that can process get and post?</p>
19
2009-07-01T19:50:19Z
1,071,260
<p>In Python, the way to produce a website is to use a framework. Most of the popular (and actively maintained/supported) frameworks have already been mentioned. </p> <p>In general, I do not view Djano or Turbogears as "huge", I view them as "complete." Each will let you build a database backed, dynamic website. The preference for one over the other is more about style than it is about features. </p> <p><a href="http://www.zope.org/" rel="nofollow">Zope</a> on the other hand, does feel "big". Zope is also "enterprise" class in terms of the features that are included out of the box. One very nice thing is that you can use the ZODB (Zope Object Database) without using the rest of Zope. </p> <p>It would certainly help if we knew what kinds of websites you were interested in developing, as that might help to narrow the suggestions. </p>
2
2009-07-01T20:36:01Z
[ "python" ]
Writing a website in Python
1,070,999
<p>I'm pretty proficient in PHP, but want to try something new.</p> <p>I'm also know a bit of Python, enough to do the basics of the basics, but haven't used in a web design type situation.</p> <p>I've just written this, which works:</p> <pre><code>#!/usr/bin/python def main(): print "Content-type: text/html" print print "&lt;html&gt;&lt;head&gt;" print "&lt;title&gt;Hello World from Python&lt;/title&gt;" print "&lt;/head&gt;&lt;body&gt;" print "Hello World!" print "&lt;/body&gt;&lt;/html&gt;" if __name__ == "__main__": main() </code></pre> <p>Thing is, that this seems pretty cumbersome. Without using something huge like django, what's the best way to write scripts that can process get and post?</p>
19
2009-07-01T19:50:19Z
1,075,964
<p>In web2py the previous code would be</p> <p>in controller <code>default.py</code>:</p> <pre><code>def main(): return dict(message="Hello World") </code></pre> <p>in view <code>default/main.html</code>:</p> <pre><code>&lt;html&gt;&lt;head&gt; &lt;title&gt;Hello World from Python&lt;/title&gt; &lt;/head&gt;&lt;body&gt; {{=message}} &lt;/body&gt;&lt;/html&gt; </code></pre> <p>nothing else, no installation, no configuration, you can edit the two files above directly on the web via the admin interface. web2py is based on wsgi but works also with cgi, mod_python, mod_proxy and fastcgi if mod_wsgi is not available.</p>
2
2009-07-02T18:30:47Z
[ "python" ]
Pylons: address already in use when trying to serve
1,071,071
<p>I'm running pylons and I did this: paster server development.ini It's running on :5000</p> <p>But when I try to run the command again: paster serve development.ini</p> <p>I get this message: socket.error: [Errno 98] Address already in use</p> <p>Any ideas?</p>
3
2009-07-01T20:03:07Z
1,071,115
<p>Normally that means it's still running, but that should only happen if it's in daemon mode. After you started it, do you get a command prompt, or do you have to stop it with Ctrl-C?</p> <p>If you get a command prompt back it's deamon mode and you have to stop it with</p> <pre><code>paster server development.ini stop </code></pre> <p>If you have stopped it with Ctrl-C (and not Ctrl-Z of course), I have no idea.</p>
3
2009-07-01T20:12:19Z
[ "python", "nginx", "pylons", "paste", "paster" ]
Pylons: address already in use when trying to serve
1,071,071
<p>I'm running pylons and I did this: paster server development.ini It's running on :5000</p> <p>But when I try to run the command again: paster serve development.ini</p> <p>I get this message: socket.error: [Errno 98] Address already in use</p> <p>Any ideas?</p>
3
2009-07-01T20:03:07Z
1,071,117
<p>As I understand your question, you start some application to listen on port 5000. Then without stopping it (?), you try to start another instance to listen on het same port? If so, you won't succeed.</p> <p>You can always check what application is listening on what port number by using <code>netstat</code> (for both Windows and UNIX-like systems, I have no experience with others).</p>
2
2009-07-01T20:12:30Z
[ "python", "nginx", "pylons", "paste", "paster" ]
Pylons: address already in use when trying to serve
1,071,071
<p>I'm running pylons and I did this: paster server development.ini It's running on :5000</p> <p>But when I try to run the command again: paster serve development.ini</p> <p>I get this message: socket.error: [Errno 98] Address already in use</p> <p>Any ideas?</p>
3
2009-07-01T20:03:07Z
2,933,318
<p>This has also happened to me when the server died unexpectedly, and didn't close it's socket's properly. Essentially, the socket is still listed as open with the operating system, even though the process has died. I've found if I wait for 30-60 seconds, the OS will realize the associated process has died, and cleanup the sockets automatically.</p>
1
2010-05-29T00:52:52Z
[ "python", "nginx", "pylons", "paste", "paster" ]
Pylons: address already in use when trying to serve
1,071,071
<p>I'm running pylons and I did this: paster server development.ini It's running on :5000</p> <p>But when I try to run the command again: paster serve development.ini</p> <p>I get this message: socket.error: [Errno 98] Address already in use</p> <p>Any ideas?</p>
3
2009-07-01T20:03:07Z
8,516,490
<p>your default port 8080 is using. you should add '-p 10000' after command to take port 10000</p>
0
2011-12-15T07:27:12Z
[ "python", "nginx", "pylons", "paste", "paster" ]
Pylons: address already in use when trying to serve
1,071,071
<p>I'm running pylons and I did this: paster server development.ini It's running on :5000</p> <p>But when I try to run the command again: paster serve development.ini</p> <p>I get this message: socket.error: [Errno 98] Address already in use</p> <p>Any ideas?</p>
3
2009-07-01T20:03:07Z
9,109,982
<p>I've found this trick in a forum:</p> <p>This will kill all programs listening to port 5000</p> <pre><code>kill -9 `fuser -n tcp 5000` </code></pre>
15
2012-02-02T09:35:17Z
[ "python", "nginx", "pylons", "paste", "paster" ]