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
AuiNotebook, where did the event happend
578,800
<p>How can I find out from which AuiNotebook page an event occurred?</p> <p>EDIT: Sorry about that. Here are a code example. How do I find the notebook page from witch the mouse was clicked in?</p> <pre><code>#!/usr/bin/python #12_aui_notebook1.py import wx import wx.lib.inspection class MyFrame(wx.Frame): def __init__(self, *args, **kwds): wx.Frame.__init__(self, *args, **kwds) self.nb = wx.aui.AuiNotebook(self) self.new_panel('Pane 1') self.new_panel('Pane 2') self.new_panel('Pane 3') def new_panel(self, nm): pnl = wx.Panel(self) self.nb.AddPage(pnl, nm) self.sizer = wx.BoxSizer() self.sizer.Add(self.nb, 1, wx.EXPAND) self.SetSizer(self.sizer) pnl.Bind(wx.EVT_LEFT_DOWN, self.click) def click(self, event): print 'Mouse click' #How can I find out from witch page this click came from? class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1, '12_aui_notebook1.py') frame.Show() self.SetTopWindow(frame) return 1 if __name__ == "__main__": app = MyApp(0) # wx.lib.inspection.InspectionTool().Show() app.MainLoop() </code></pre> <p>Oerjan Pettersen</p>
1
2009-02-23T18:45:11Z
580,522
<p>For a mouse click you can assume the current selected page is the one that got the click. I added a few lines to your code. See comments</p> <pre><code>def new_panel(self, nm): pnl = wx.Panel(self) # just to debug, I added a string attribute to the panel # don't you love dynamic languages? :) pnl.identifierTag = nm self.nb.AddPage(pnl, nm) self.sizer = wx.BoxSizer() self.sizer.Add(self.nb, 1, wx.EXPAND) self.SetSizer(self.sizer) pnl.Bind(wx.EVT_LEFT_DOWN, self.click) def click(self, event): print 'Mouse click' # get the current selected page page = self.nb.GetPage(self.nb.GetSelection()) # notice that it is the panel that you created in new_panel print page.identifierTag </code></pre>
1
2009-02-24T05:02:36Z
[ "python", "wxpython", "wxwidgets" ]
Need help understanding function passing in Python
578,812
<p>I am trying to teach myself Python by working through some problems I came up with, and I need some help understanding how to pass functions.</p> <p>Let's say I am trying to predict tomorrow's temperature based on today's and yesterday's temperature, and I have written the following function:</p> <pre><code>def predict_temp(temp_today, temp_yest, k1, k2): return k1*temp_today + k2*temp_yest </code></pre> <p>And I have also written an error function to compare a list of predicted temperatures with actual temperatures and return the mean absolute error:</p> <pre><code>def mean_abs_error(predictions, expected): return sum([abs(x - y) for (x,y) in zip(predictions,expected)]) / float(len(predictions)) </code></pre> <p>Now if I have a list of daily temperatures for some interval in the past, I can see how my prediction function would have done <strong>with specific k1 and k2 parameters</strong> like this:</p> <pre><code>&gt;&gt;&gt; past_temps = [41, 35, 37, 42, 48, 30, 39, 42, 33] &gt;&gt;&gt; pred_temps = [predict_temp(past_temps[i-1],past_temps[i-2],0.5,0.5) for i in xrange(2,len(past_temps))] &gt;&gt;&gt; print pred_temps [38.0, 36.0, 39.5, 45.0, 39.0, 34.5, 40.5] &gt;&gt;&gt; print mean_abs_error(pred_temps, past_temps[2:]) 6.5 </code></pre> <p><strong>But how do I design a function to minimize my parameters k1 and k2 of my predict_temp function given an error function and my past_temps data?</strong></p> <p>Specifically I would like to write a function minimize(args*) that takes a prediction function, an error function, some training data, and that uses some search/optimization method (gradient descent for example) to estimate and return the values of k1 and k2 that minimize my error given the data?</p> <p>I am not asking how to implement the optimization method. Assume I can do that. Rather, I would just like to know <strong>how to pass my predict and error functions</strong> (and my data) to my minimize function, and <strong>how to tell my minimize function that it should optimize the parameters k1 and k2</strong>, so that my minimize function can automatically search a bunch of different settings of k1 and k2, applying my prediction function with those parameters each time to the data and computing error (like I did manually for k1=0.5 and k2=0.5 above) and then return the best results.</p> <p>I would like to be able to pass these functions so I can easily swap in different prediction and error functions (differing by more than just parameter settings that is). Each prediction function might have a different number of free parameters.</p> <p>My minimize function should look something like this, but I don't know how to proceed:</p> <pre><code>def minimize(prediction_function, which_args_to_optimize, error_function, data): # 1: guess initial parameters # 2: apply prediction function with current parameters to data to compute predictions # 3: use error function to compute error between predictions and data # 4: if stopping criterion is met, return parameters # 5: update parameters # 6: GOTO 2 </code></pre> <p>Edit: It's that easy?? This is no fun. I am going back to Java. </p> <p>On a more serious note, I think I was also getting hung up on how to use different prediction functions with different numbers of parameters to tune. If I just take all the free parameters in as one tuple I can keep the form of the function the same so it easy to pass and use.</p>
4
2009-02-23T18:47:43Z
578,855
<p>Function passing in Python is easy, you just use the name of the function as a variable which contains the function itself.</p> <pre><code>def predict(...): ... minimize(predict, ..., mean_abs_error, ...) </code></pre> <p>As for the rest of the question: I'd suggest looking at the way <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html#scipy.optimize.leastsq" rel="nofollow">SciPy implements this</a> as a model. Basically, they have a function <code>leastsq</code> which minimizes the sum of the squares of the residuals (I presume you know what least-squares minimization is ;-). What you pass to <code>leastsq</code> is a function to compute the residuals, initial guesses for the parameters, and an arbitrary parameter which gets passed on to your residual-computing function (the closure), which includes the data:</p> <pre><code># params will be an array of your k's, i.e. [k1, k2] def residuals(params, measurements, times): return predict(params, times) - measurements leastsq(residuals, initial_parameters, args = (measurements, times)) </code></pre> <p>Note that SciPy doesn't actually concern itself with how you come up with the residuals. The <code>measurements</code> array is just passed unaltered to your <code>residuals</code> function.</p> <p>I can look up an example I did recently if you want more information - or you can find examples online, of course, but in my experience they're not quite as clear. The particular bit of code I wrote would relate well to your scenario.</p>
2
2009-02-23T18:55:35Z
[ "python" ]
Need help understanding function passing in Python
578,812
<p>I am trying to teach myself Python by working through some problems I came up with, and I need some help understanding how to pass functions.</p> <p>Let's say I am trying to predict tomorrow's temperature based on today's and yesterday's temperature, and I have written the following function:</p> <pre><code>def predict_temp(temp_today, temp_yest, k1, k2): return k1*temp_today + k2*temp_yest </code></pre> <p>And I have also written an error function to compare a list of predicted temperatures with actual temperatures and return the mean absolute error:</p> <pre><code>def mean_abs_error(predictions, expected): return sum([abs(x - y) for (x,y) in zip(predictions,expected)]) / float(len(predictions)) </code></pre> <p>Now if I have a list of daily temperatures for some interval in the past, I can see how my prediction function would have done <strong>with specific k1 and k2 parameters</strong> like this:</p> <pre><code>&gt;&gt;&gt; past_temps = [41, 35, 37, 42, 48, 30, 39, 42, 33] &gt;&gt;&gt; pred_temps = [predict_temp(past_temps[i-1],past_temps[i-2],0.5,0.5) for i in xrange(2,len(past_temps))] &gt;&gt;&gt; print pred_temps [38.0, 36.0, 39.5, 45.0, 39.0, 34.5, 40.5] &gt;&gt;&gt; print mean_abs_error(pred_temps, past_temps[2:]) 6.5 </code></pre> <p><strong>But how do I design a function to minimize my parameters k1 and k2 of my predict_temp function given an error function and my past_temps data?</strong></p> <p>Specifically I would like to write a function minimize(args*) that takes a prediction function, an error function, some training data, and that uses some search/optimization method (gradient descent for example) to estimate and return the values of k1 and k2 that minimize my error given the data?</p> <p>I am not asking how to implement the optimization method. Assume I can do that. Rather, I would just like to know <strong>how to pass my predict and error functions</strong> (and my data) to my minimize function, and <strong>how to tell my minimize function that it should optimize the parameters k1 and k2</strong>, so that my minimize function can automatically search a bunch of different settings of k1 and k2, applying my prediction function with those parameters each time to the data and computing error (like I did manually for k1=0.5 and k2=0.5 above) and then return the best results.</p> <p>I would like to be able to pass these functions so I can easily swap in different prediction and error functions (differing by more than just parameter settings that is). Each prediction function might have a different number of free parameters.</p> <p>My minimize function should look something like this, but I don't know how to proceed:</p> <pre><code>def minimize(prediction_function, which_args_to_optimize, error_function, data): # 1: guess initial parameters # 2: apply prediction function with current parameters to data to compute predictions # 3: use error function to compute error between predictions and data # 4: if stopping criterion is met, return parameters # 5: update parameters # 6: GOTO 2 </code></pre> <p>Edit: It's that easy?? This is no fun. I am going back to Java. </p> <p>On a more serious note, I think I was also getting hung up on how to use different prediction functions with different numbers of parameters to tune. If I just take all the free parameters in as one tuple I can keep the form of the function the same so it easy to pass and use.</p>
4
2009-02-23T18:47:43Z
578,869
<p>Here is an example of how to pass a function into another function. <code>apply_func_to</code> will take a function <code>f</code> and a number <code>num</code> as parameters and <code>return f(num)</code>.</p> <pre><code>def my_func(x): return x*x def apply_func_to(f, num): return f(num) &gt;&gt;&gt;apply_func_to(my_func, 2) 4 </code></pre> <p>If you wanna be clever you can use lambda (anonymous functions too). These allow you to pass functions "on the fly" without having to define them separately</p> <pre><code>&gt;&gt;&gt;apply_func_to(lambda x:x*x, 3) 9 </code></pre> <p>Hope this helps.</p>
13
2009-02-23T18:59:04Z
[ "python" ]
Need help understanding function passing in Python
578,812
<p>I am trying to teach myself Python by working through some problems I came up with, and I need some help understanding how to pass functions.</p> <p>Let's say I am trying to predict tomorrow's temperature based on today's and yesterday's temperature, and I have written the following function:</p> <pre><code>def predict_temp(temp_today, temp_yest, k1, k2): return k1*temp_today + k2*temp_yest </code></pre> <p>And I have also written an error function to compare a list of predicted temperatures with actual temperatures and return the mean absolute error:</p> <pre><code>def mean_abs_error(predictions, expected): return sum([abs(x - y) for (x,y) in zip(predictions,expected)]) / float(len(predictions)) </code></pre> <p>Now if I have a list of daily temperatures for some interval in the past, I can see how my prediction function would have done <strong>with specific k1 and k2 parameters</strong> like this:</p> <pre><code>&gt;&gt;&gt; past_temps = [41, 35, 37, 42, 48, 30, 39, 42, 33] &gt;&gt;&gt; pred_temps = [predict_temp(past_temps[i-1],past_temps[i-2],0.5,0.5) for i in xrange(2,len(past_temps))] &gt;&gt;&gt; print pred_temps [38.0, 36.0, 39.5, 45.0, 39.0, 34.5, 40.5] &gt;&gt;&gt; print mean_abs_error(pred_temps, past_temps[2:]) 6.5 </code></pre> <p><strong>But how do I design a function to minimize my parameters k1 and k2 of my predict_temp function given an error function and my past_temps data?</strong></p> <p>Specifically I would like to write a function minimize(args*) that takes a prediction function, an error function, some training data, and that uses some search/optimization method (gradient descent for example) to estimate and return the values of k1 and k2 that minimize my error given the data?</p> <p>I am not asking how to implement the optimization method. Assume I can do that. Rather, I would just like to know <strong>how to pass my predict and error functions</strong> (and my data) to my minimize function, and <strong>how to tell my minimize function that it should optimize the parameters k1 and k2</strong>, so that my minimize function can automatically search a bunch of different settings of k1 and k2, applying my prediction function with those parameters each time to the data and computing error (like I did manually for k1=0.5 and k2=0.5 above) and then return the best results.</p> <p>I would like to be able to pass these functions so I can easily swap in different prediction and error functions (differing by more than just parameter settings that is). Each prediction function might have a different number of free parameters.</p> <p>My minimize function should look something like this, but I don't know how to proceed:</p> <pre><code>def minimize(prediction_function, which_args_to_optimize, error_function, data): # 1: guess initial parameters # 2: apply prediction function with current parameters to data to compute predictions # 3: use error function to compute error between predictions and data # 4: if stopping criterion is met, return parameters # 5: update parameters # 6: GOTO 2 </code></pre> <p>Edit: It's that easy?? This is no fun. I am going back to Java. </p> <p>On a more serious note, I think I was also getting hung up on how to use different prediction functions with different numbers of parameters to tune. If I just take all the free parameters in as one tuple I can keep the form of the function the same so it easy to pass and use.</p>
4
2009-02-23T18:47:43Z
579,126
<p>As <a href="http://stackoverflow.com/questions/578812/need-help-understanding-function-passing-in-python/578855#578855">David</a> and and <a href="http://stackoverflow.com/questions/578812/need-help-understanding-function-passing-in-python/578869#578869">Il-Bhima</a> note, functions can be passed into other functions just like any other type of object. When you pass a function in, you simply call it like you ordinarily would. People sometimes refer to this ability by saying that functions are <em>first class</em> in Python. At a slightly greater level of detail, you should think of functions in Python as being one type of <em>callable object</em>. Another important type of callable object in Python is class objects; in this case, calling a class object creates an instance of that object. This concept is discussed in detail <a href="http://docs.python.org/reference/expressions.html#id9" rel="nofollow">here</a>.</p> <p>Generically, you will probably want to leverage the positional and/or keyword argument feature of Python, as described <a href="http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions" rel="nofollow">here</a>. This will allow you to write a generic minimizer that can minimize prediction functions taking different sets of parameters. I've written an example---it's more complicated than I'd like (uses generators!) but it works for prediction functions with arbitrary parameters. I've glossed over a few details, but this should get you started:</p> <pre><code>def predict(data, k1=None, k2=None): """Make the prediction.""" pass def expected(data): """Expected results from data.""" pass def mean_abs_err(pred, exp): """Compute mean absolute error.""" pass def gen_args(pred_args, args_to_opt): """Update prediction function parameters. pred_args : a dict to update args_to_opt : a dict of arguments/iterables to apply to pred_args This is a generator that updates a number of variables over a given numerical range. Equivalent to itertools.product. """ base_args = pred_args.copy() #don't modify input argnames = args_to_opt.keys() argvals = args_to_opt.values() result = [[]] # Generate the results for argv in argvals: result = [x+[y] for x in result for y in argv] for prod in result: base_args.update(zip(argnames, prod)) yield base_args def minimize(pred_fn, pred_args, args_to_opt, err_fn, data): """Minimize pred_fn(data) over a set of parameters. pred_fn : function used to make predictions pred_args : dict of keyword arguments to pass to pred_fn args_to_opt : a dict of arguments/iterables to apply to pred_args err_fn : function used to compute error data : data to use in the optimization Returns a tuple (error, parameters) of the best set of input parameters. """ results = [] for new_args in gen_args(pred_args, args_to_opt): pred = pred_fn(data, **new_args) # Unpack dictionary err = err_fn(pred, expected(data)) results.append((err, new_args)) return sorted(results)[0] const_args = {k1: 1} opt_args = {k2: range(10)} data = [] # Whatever data you like. minimize(predict, const_args, opt_args, mean_abs_err, data) </code></pre>
1
2009-02-23T20:10:19Z
[ "python" ]
Python package import error
578,983
<p>I'm trying to package my modules, but I can't seem to get it working. </p> <p>My directory tree is something like the following:</p> <pre><code>snappy/ __init__.py main/ __init__.py main.py config.py ... ... </code></pre> <p>and the code I'm using is</p> <pre><code>from snappy.main.config import * </code></pre> <p>I'm getting the error:</p> <pre><code>ImportError: No module named snappy.main.config </code></pre> <p>Any ideas what's going wrong? This is using Python 2.5 on Ubuntu 8.10.</p> <p>Thanks in advance for your help.</p>
3
2009-02-23T19:27:23Z
578,993
<p>Is the parent directory of <code>snappy</code> in <code>sys.path</code>? If it's not, that's the only thing I can think of that would be causing your error.</p>
5
2009-02-23T19:29:12Z
[ "python", "package", "python-import" ]
Python package import error
578,983
<p>I'm trying to package my modules, but I can't seem to get it working. </p> <p>My directory tree is something like the following:</p> <pre><code>snappy/ __init__.py main/ __init__.py main.py config.py ... ... </code></pre> <p>and the code I'm using is</p> <pre><code>from snappy.main.config import * </code></pre> <p>I'm getting the error:</p> <pre><code>ImportError: No module named snappy.main.config </code></pre> <p>Any ideas what's going wrong? This is using Python 2.5 on Ubuntu 8.10.</p> <p>Thanks in advance for your help.</p>
3
2009-02-23T19:27:23Z
579,000
<p>It depends on where your script using the import resides and your system PYTHONPATH. Basically, to have that import working you should run your script (the one having the import) in the parent directory of snappy or your script should change sys.path to include it.</p> <p>./alex</p>
5
2009-02-23T19:31:05Z
[ "python", "package", "python-import" ]
Is there a pattern for propagating details of both errors and warnings?
579,097
<p>Is there a common pattern for propagating details of both errors and warnings? By <em>errors</em> I mean serious problems that should cause the flow of code to stop. By <em>warnings</em> I mean issues that merit informing the user of a problem, but are too trivial to stop program flow.</p> <p>I currently use exceptions to deal with hard errors, and the Python logging framework to record warnings. But now I want to record warnings in a database field of the record currently being processed instead. I guess, I want the warnings to bubble up in the same manner as exceptions, but without stopping program flow.</p> <pre><code>&gt;&gt;&gt; import logging &gt;&gt;&gt; &gt;&gt;&gt; def process_item(item): ... if item: ... if item == 'broken': ... logging.warning('soft error, continue with next item') ... else: ... raise Exception('hard error, cannot continue') ... &gt;&gt;&gt; process_item('good') &gt;&gt;&gt; process_item(None) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 6, in process_item Exception: hard error, cannot continue &gt;&gt;&gt; process_item('broken') WARNING:root:soft error, continue with next item </code></pre> <p><em>This example (and my current problem) is in Python, but it should apply to other languages with exceptions too.</em></p> <p><hr /></p> <p>Following <a href="http://stackoverflow.com/users/56541/david">David</a>'s suggestion and a brief play with the example below, Python's <code>warnings</code> module is the way to go.</p> <pre><code>import warnings class MyWarning(Warning): pass def causes_warnings(): print 'enter causes_warnings' warnings.warn("my warning", MyWarning) print 'leave causes_warnings' def do_stuff(): print 'enter do_stuff' causes_warnings() causes_warnings() causes_warnings() print 'leave do_stuff' with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") # Trigger a number of warnings. do_stuff() # Do something (not very) useful with the warnings generated print 'Warnings:',','.join([str(warning.message) for warning in w]) </code></pre> <p>Output:</p> <pre><code>enter do_stuff enter causes_warnings leave causes_warnings enter causes_warnings leave causes_warnings enter causes_warnings leave causes_warnings leave do_stuff Warnings: my warning,my warning,my warning </code></pre> <p>Note: Python 2.6+ is required for <code>catch_warnings</code>.</p>
6
2009-02-23T19:58:15Z
579,102
<p>Serious errors should bubble up, warning should just be logged in place without throwing exceptions.</p>
-1
2009-02-23T20:00:00Z
[ "python", "design-patterns", "error-handling", "warnings" ]
Is there a pattern for propagating details of both errors and warnings?
579,097
<p>Is there a common pattern for propagating details of both errors and warnings? By <em>errors</em> I mean serious problems that should cause the flow of code to stop. By <em>warnings</em> I mean issues that merit informing the user of a problem, but are too trivial to stop program flow.</p> <p>I currently use exceptions to deal with hard errors, and the Python logging framework to record warnings. But now I want to record warnings in a database field of the record currently being processed instead. I guess, I want the warnings to bubble up in the same manner as exceptions, but without stopping program flow.</p> <pre><code>&gt;&gt;&gt; import logging &gt;&gt;&gt; &gt;&gt;&gt; def process_item(item): ... if item: ... if item == 'broken': ... logging.warning('soft error, continue with next item') ... else: ... raise Exception('hard error, cannot continue') ... &gt;&gt;&gt; process_item('good') &gt;&gt;&gt; process_item(None) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 6, in process_item Exception: hard error, cannot continue &gt;&gt;&gt; process_item('broken') WARNING:root:soft error, continue with next item </code></pre> <p><em>This example (and my current problem) is in Python, but it should apply to other languages with exceptions too.</em></p> <p><hr /></p> <p>Following <a href="http://stackoverflow.com/users/56541/david">David</a>'s suggestion and a brief play with the example below, Python's <code>warnings</code> module is the way to go.</p> <pre><code>import warnings class MyWarning(Warning): pass def causes_warnings(): print 'enter causes_warnings' warnings.warn("my warning", MyWarning) print 'leave causes_warnings' def do_stuff(): print 'enter do_stuff' causes_warnings() causes_warnings() causes_warnings() print 'leave do_stuff' with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") # Trigger a number of warnings. do_stuff() # Do something (not very) useful with the warnings generated print 'Warnings:',','.join([str(warning.message) for warning in w]) </code></pre> <p>Output:</p> <pre><code>enter do_stuff enter causes_warnings leave causes_warnings enter causes_warnings leave causes_warnings enter causes_warnings leave causes_warnings leave do_stuff Warnings: my warning,my warning,my warning </code></pre> <p>Note: Python 2.6+ is required for <code>catch_warnings</code>.</p>
6
2009-02-23T19:58:15Z
579,117
<p>Look into Python's <code>warnings</code> module, <a href="http://docs.python.org/library/warnings.html" rel="nofollow">http://docs.python.org/library/warnings.html</a></p> <p>I don't think there's much you can say about this problem without specifying the language, as non-terminal error handling varies greatly from one language to another.</p>
7
2009-02-23T20:05:54Z
[ "python", "design-patterns", "error-handling", "warnings" ]
Instantiating a python class in C#
579,272
<p>I've written a class in python that I want to wrap into a .net assembly via IronPython and instantiate in a C# application. I've migrated the class to IronPython, created a library assembly and referenced it. Now, how do I actually get an instance of that class?</p> <p>The class looks (partially) like this:</p> <pre><code>class PokerCard: "A card for playing poker, immutable and unique." def __init__(self, cardName): </code></pre> <p>The test stub I wrote in C# is:</p> <pre><code>using System; namespace pokerapp { class Program { static void Main(string[] args) { var card = new PokerCard(); // I also tried new PokerCard("Ah") Console.WriteLine(card.ToString()); Console.ReadLine(); } } } </code></pre> <p>What do I have to do in order to instantiate this class in C#?</p>
36
2009-02-23T20:47:25Z
579,368
<p>I have searched high and low and I am afraid that there does not seem to be much information pertaining to this. I am pretty much certain that no one has devised a way to do this in the clean manner that you would like.</p> <p>The main reason I think this is a problem is that in order to see the <code>PokerCard</code> type in your C# application you would have to compile your Python code to IL. I don't believe that there are any Python<code>-&gt;</code>IL compilers out there.</p>
-4
2009-02-23T21:09:38Z
[ "c#", ".net", "python", "ironpython", "cross-language" ]
Instantiating a python class in C#
579,272
<p>I've written a class in python that I want to wrap into a .net assembly via IronPython and instantiate in a C# application. I've migrated the class to IronPython, created a library assembly and referenced it. Now, how do I actually get an instance of that class?</p> <p>The class looks (partially) like this:</p> <pre><code>class PokerCard: "A card for playing poker, immutable and unique." def __init__(self, cardName): </code></pre> <p>The test stub I wrote in C# is:</p> <pre><code>using System; namespace pokerapp { class Program { static void Main(string[] args) { var card = new PokerCard(); // I also tried new PokerCard("Ah") Console.WriteLine(card.ToString()); Console.ReadLine(); } } } </code></pre> <p>What do I have to do in order to instantiate this class in C#?</p>
36
2009-02-23T20:47:25Z
579,609
<p>IronPython classes are <em>not</em> .NET classes. They are instances of IronPython.Runtime.Types.PythonType which is the Python metaclass. This is because Python classes are dynamic and support addition and removal of methods at runtime, things you cannot do with .NET classes.</p> <p>To use Python classes in C# you will need to use the ObjectOperations class. This class allows you to operate on python types and instances in the semantics of the language itself. e.g. it uses the magic methods when appropriate, auto-promotes integers to longs etc. You can find out more about ObjectOperations by looking at the source or using reflector.</p> <p>Here is an example. Calculator.py contains a simple class:</p> <pre><code>class Calculator(object): def add(self, a, b): return a + b </code></pre> <p>You can use it from your pre .NET 4.0 C# code like this:</p> <pre><code>ScriptEngine engine = Python.CreateEngine(); ScriptSource source = engine.CreateScriptSourceFromFile("Calculator.py"); ScriptScope scope = engine.CreateScope(); ObjectOperations op = engine.Operations; source.Execute(scope); // class object created object klaz = scope.GetVariable("Calculator"); // get the class object object instance = op.Call(klaz); // create the instance object method = op.GetMember(instance, "add"); // get a method int result = (int)op.Call(method, 4, 5); // call method and get result (9) </code></pre> <p>You will need to reference the assemblies IronPython.dll, Microsoft.Scripting and Microsoft.Scripting.Core.</p> <p>C# 4 made this much easier with the <em>new</em> dynamic type.</p> <pre><code>ScriptEngine engine = Python.CreateEngine(); ScriptSource source = engine.CreateScriptSourceFromFile("Calculator.py"); ScriptScope scope = engine.CreateScope(); source.Execute(scope); dynamic Calculator = scope.GetVariable("Calculator"); dynamic calc = Calculator(); int result = calc.add(4, 5); </code></pre> <p>If you are using Visual Studio 2010 or later with NuGet support simply execute this to download and reference the appropriate libraries.</p> <pre><code>Install-Package IronPython </code></pre>
46
2009-02-23T22:14:43Z
[ "c#", ".net", "python", "ironpython", "cross-language" ]
Instantiating a python class in C#
579,272
<p>I've written a class in python that I want to wrap into a .net assembly via IronPython and instantiate in a C# application. I've migrated the class to IronPython, created a library assembly and referenced it. Now, how do I actually get an instance of that class?</p> <p>The class looks (partially) like this:</p> <pre><code>class PokerCard: "A card for playing poker, immutable and unique." def __init__(self, cardName): </code></pre> <p>The test stub I wrote in C# is:</p> <pre><code>using System; namespace pokerapp { class Program { static void Main(string[] args) { var card = new PokerCard(); // I also tried new PokerCard("Ah") Console.WriteLine(card.ToString()); Console.ReadLine(); } } } </code></pre> <p>What do I have to do in order to instantiate this class in C#?</p>
36
2009-02-23T20:47:25Z
2,722,635
<p>Now that .Net 4.0 is released and has the dynamic type, this example should be updated. Using the same python file as in m-sharp's original answer:</p> <pre class="lang-py prettyprint-override"><code>class Calculator(object): def add(self, a, b): return a + b </code></pre> <p>Here is how you would call it using .Net 4.0:</p> <pre class="lang-cs prettyprint-override"><code>string scriptPath = "Calculator.py"; ScriptEngine engine = Python.CreateEngine(); engine.SetSearchPaths(new string[] {"Path to your lib's here. EG:", "C:\\Program Files (x86)\\IronPython 2.7.1\\Lib"}); ScriptSource source = engine.CreateScriptSourceFromFile(scriptPath); ScriptScope scope = engine.CreateScope(); ObjectOperations op = engine.Operations; source.Execute(scope); dynamic Calculator = scope.GetVariable("Calculator"); dynamic calc = Calculator(); return calc.add(x,y); </code></pre> <p>Again, you need to add references to IronPython.dll and Microsoft.Scripting.</p> <p>As you can see, the initial setting up and creating of the source file is the same. </p> <p>But once the source is succesfully executed, working with the python functions is far easier thanks to the new "dynamic" keyword.</p>
30
2010-04-27T15:39:13Z
[ "c#", ".net", "python", "ironpython", "cross-language" ]
Instantiating a python class in C#
579,272
<p>I've written a class in python that I want to wrap into a .net assembly via IronPython and instantiate in a C# application. I've migrated the class to IronPython, created a library assembly and referenced it. Now, how do I actually get an instance of that class?</p> <p>The class looks (partially) like this:</p> <pre><code>class PokerCard: "A card for playing poker, immutable and unique." def __init__(self, cardName): </code></pre> <p>The test stub I wrote in C# is:</p> <pre><code>using System; namespace pokerapp { class Program { static void Main(string[] args) { var card = new PokerCard(); // I also tried new PokerCard("Ah") Console.WriteLine(card.ToString()); Console.ReadLine(); } } } </code></pre> <p>What do I have to do in order to instantiate this class in C#?</p>
36
2009-02-23T20:47:25Z
17,046,283
<p>I am updating the above example provided by Clever Human for compiled IronPython classes (dll) instead of IronPython source code in a .py file.</p> <pre><code># Compile IronPython calculator class to a dll clr.CompileModules("calculator.dll", "calculator.py") </code></pre> <p>C# 4.0 code with the new dynamic type is as follows:</p> <pre><code>// IRONPYTHONPATH environment variable is not required. Core ironpython dll paths should be part of operating system path. ScriptEngine pyEngine = Python.CreateEngine(); Assembly myclass = Assembly.LoadFile(Path.GetFullPath("calculator.dll")); pyEngine.Runtime.LoadAssembly(myclass); ScriptScope pyScope = pyEngine.Runtime.ImportModule("calculator"); dynamic Calculator = pyScope.GetVariable("Calculator"); dynamic calc = Calculator(); int result = calc.add(4, 5); </code></pre> <p>References:</p> <ol> <li><a href="http://www.ironpython.info/index.php/Using_Compiled_Python_Classes_from_.NET/CSharp_IP_2.6" rel="nofollow">Using Compiled Python Classes from .NET/CSharp IP 2.6</a></li> <li><a href="http://blogs.msdn.com/b/srivatsn/archive/2008/08/06/static-compilation-of-ironpython-scripts.aspx" rel="nofollow">Static Compilation of IronPython scripts</a></li> </ol>
0
2013-06-11T14:12:29Z
[ "c#", ".net", "python", "ironpython", "cross-language" ]
formatting long numbers as strings in python
579,310
<p>What is an easy way in Python to format integers into strings representing thousands with K, and millions with M, and leaving just couple digits after comma?</p> <p>I'd like to show 7436313 as 7.44M, and 2345 as 2,34K.</p> <p>Is there some % string formatting operator available for that? Or that could be done only by actually dividing by 1000 in a loop and constructing result string step by step?</p>
10
2009-02-23T20:55:58Z
579,343
<p>No String Formatting Operator, <a href="http://docs.python.org/library/stdtypes.html#string-formatting-operations" rel="nofollow">according to the docs</a>. I've never heard of such a thing, so you may have to roll your own, as you suggest.</p>
0
2009-02-23T21:02:49Z
[ "python", "formatting", "string", "integer" ]
formatting long numbers as strings in python
579,310
<p>What is an easy way in Python to format integers into strings representing thousands with K, and millions with M, and leaving just couple digits after comma?</p> <p>I'd like to show 7436313 as 7.44M, and 2345 as 2,34K.</p> <p>Is there some % string formatting operator available for that? Or that could be done only by actually dividing by 1000 in a loop and constructing result string step by step?</p>
10
2009-02-23T20:55:58Z
579,349
<p>I don't think there are format operators for that, but you can simply divide by 1000 until the result is between 1 and 999 and then use a format string for 2 digits after comma. Unit is a single character (or perhaps a small string) in most cases, which you can store in a string or array and iterate through it after each divide.</p>
0
2009-02-23T21:05:36Z
[ "python", "formatting", "string", "integer" ]
formatting long numbers as strings in python
579,310
<p>What is an easy way in Python to format integers into strings representing thousands with K, and millions with M, and leaving just couple digits after comma?</p> <p>I'd like to show 7436313 as 7.44M, and 2345 as 2,34K.</p> <p>Is there some % string formatting operator available for that? Or that could be done only by actually dividing by 1000 in a loop and constructing result string step by step?</p>
10
2009-02-23T20:55:58Z
579,373
<p>I don't know of any built-in capability like this, but here are a couple of list threads that may help:</p> <p><a href="http://coding.derkeiler.com/Archive/Python/comp.lang.python/2005-09/msg03327.html" rel="nofollow">http://coding.derkeiler.com/Archive/Python/comp.lang.python/2005-09/msg03327.html</a> <a href="http://mail.python.org/pipermail/python-list/2008-August/503417.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2008-August/503417.html</a></p>
0
2009-02-23T21:10:45Z
[ "python", "formatting", "string", "integer" ]
formatting long numbers as strings in python
579,310
<p>What is an easy way in Python to format integers into strings representing thousands with K, and millions with M, and leaving just couple digits after comma?</p> <p>I'd like to show 7436313 as 7.44M, and 2345 as 2,34K.</p> <p>Is there some % string formatting operator available for that? Or that could be done only by actually dividing by 1000 in a loop and constructing result string step by step?</p>
10
2009-02-23T20:55:58Z
579,376
<p>I don't think there's a built-in function that does that. You'll have to roll your own, e.g.:</p> <pre><code>def human_format(num): magnitude = 0 while abs(num) &gt;= 1000: magnitude += 1 num /= 1000.0 # add more suffixes if you need them return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude]) print('the answer is %s' % human_format(7436313)) # prints 'the answer is 7.44M' </code></pre>
20
2009-02-23T21:11:36Z
[ "python", "formatting", "string", "integer" ]
WSGI byte ranges serving
579,426
<p>I'm looking into supporting <a href="http://en.wikipedia.org/wiki/Byte%5Fserving" rel="nofollow">HTTP/1.1 Byte serving</a> in WSGI server/application for:</p> <ul> <li>resuming partial downloads</li> <li>multi-part downloads</li> <li>better streaming</li> </ul> <p><a href="http://www.python.org/dev/peps/pep-0333/#other-http-features" rel="nofollow">WSGI PEP 333</a> mentions that WSGI server may implement handling of byte serving (from <a href="http://tools.ietf.org/html/rfc2616" rel="nofollow">RFC 2616</a> section 14.35.2 defines Accept-Range/Range/Content-Range response/request/response headers) and application should implement it if announces the capability:</p> <blockquote> <p>A server may transmit byte ranges of the application's response if requested by the client, and the application doesn't natively support byte ranges. Again, however, the application should perform this function on its own if desired.</p> </blockquote> <p>I've performed some Googling but found little information upon which of the available WSGI servers/middleware/applications implement Byte-Ranges? Does anyone has an experience in the field and can hint me place to dig further?</p> <p>EDIT: Can anyone comment, how I can enhance the question to be able to find an answer?</p>
5
2009-02-23T21:22:48Z
594,496
<p>I think <a href="http://pythonpaste.org/webob/" rel="nofollow">webob</a> may do the trick, see the end of the <a href="http://pythonpaste.org/webob/file-example.html" rel="nofollow">file example</a> for a range request implementation which efficiently seeks into the file being served.</p>
3
2009-02-27T12:10:21Z
[ "python", "http", "http-headers", "wsgi", "middleware" ]
WSGI byte ranges serving
579,426
<p>I'm looking into supporting <a href="http://en.wikipedia.org/wiki/Byte%5Fserving" rel="nofollow">HTTP/1.1 Byte serving</a> in WSGI server/application for:</p> <ul> <li>resuming partial downloads</li> <li>multi-part downloads</li> <li>better streaming</li> </ul> <p><a href="http://www.python.org/dev/peps/pep-0333/#other-http-features" rel="nofollow">WSGI PEP 333</a> mentions that WSGI server may implement handling of byte serving (from <a href="http://tools.ietf.org/html/rfc2616" rel="nofollow">RFC 2616</a> section 14.35.2 defines Accept-Range/Range/Content-Range response/request/response headers) and application should implement it if announces the capability:</p> <blockquote> <p>A server may transmit byte ranges of the application's response if requested by the client, and the application doesn't natively support byte ranges. Again, however, the application should perform this function on its own if desired.</p> </blockquote> <p>I've performed some Googling but found little information upon which of the available WSGI servers/middleware/applications implement Byte-Ranges? Does anyone has an experience in the field and can hint me place to dig further?</p> <p>EDIT: Can anyone comment, how I can enhance the question to be able to find an answer?</p>
5
2009-02-23T21:22:48Z
1,783,423
<p>You just need to use WebOb and create the response as <code>Response(conditional_request=True)</code> or <a href="http://pythonpaste.org/webob/reference.html#conditional-wsgi-application" rel="nofollow">subclass the WebOb Response object</a> making <code>conditional_request=True</code> the default.</p> <p>When <code>conditional_request=True</code> and the request asked for a range, WebOb's <code>Response.app_iter_range</code> wraps the complete response to return only the requested range.</p> <p>The <a href="http://pythonpaste.org/webob/file-example.html" rel="nofollow">WebOb file serving example</a> shows how you would implement your own <code>app_iter_range</code> for cases where it is practical to get a range of bytes without generating the whole response.</p>
0
2009-11-23T14:25:59Z
[ "python", "http", "http-headers", "wsgi", "middleware" ]
Using only the DB part of Django
579,511
<p>Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables?</p> <p>If not, what would you recommend as "the Python equivalent of Hibernate"?</p>
32
2009-02-23T21:45:54Z
579,537
<p>You can certainly use various parts of Django in a stand-alone fashion. It is after-all just a collection of Python modules, which you can import to any other code you would like to use them.</p> <p>I'd also recommend looking at <a href="http://www.sqlalchemy.org/">SQL Alchemy</a> if you are only after the ORM side of things.</p>
8
2009-02-23T21:51:51Z
[ "python", "django", "orm" ]
Using only the DB part of Django
579,511
<p>Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables?</p> <p>If not, what would you recommend as "the Python equivalent of Hibernate"?</p>
32
2009-02-23T21:45:54Z
579,548
<p>I recommend <a href="http://sqlalchemy.org">SQLAlchemy</a>. It should do all the ORM stuff, as well as basic SQL stuff.</p>
5
2009-02-23T21:52:36Z
[ "python", "django", "orm" ]
Using only the DB part of Django
579,511
<p>Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables?</p> <p>If not, what would you recommend as "the Python equivalent of Hibernate"?</p>
32
2009-02-23T21:45:54Z
579,567
<p>The short answer is: no, you can't use the Django ORM separately from Django.</p> <p>The long answer is: yes, you can if you are willing to load large parts of Django along with it. For example, the database connection that is used by Django is opened when a request to Django occurs. This happens when a signal is sent so you could ostensibly send this signal to open the connection without using the specific request mechanism. Also, you'd need to setup the various applications and settings for the Django project. </p> <p>Ultimately, it probably isn't worth your time. <a href="http://www.sqlalchemy.org/">SQL Alchemy</a> is a relatively well known Python ORM, which is actually more powerful than Django's anyway since it supports multiple database connections and connection pooling and other good stuff.</p> <p><hr /></p> <p><strong>Edit:</strong> in response to James' criticism elsewhere, I will clarify what I described in my original post. While it is gratifying that a major Django contributor has called me out, I still think I'm right :)</p> <p>First off, consider what needs to be done to use Django's ORM separate from any other part. You use one of the <a href="http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/">methods</a> described by James for doing a basic setup of Django. But a number of these methods don't allow for using the <code>syncdb</code> command, which is required to create the tables for your models. A settings.py file is needed for this, with variables not just for <code>DATABASE_*</code>, but also <code>INSTALLED_APPLICATIONS</code> with the correct paths to all models.py files.</p> <p>It is possible to roll your own solution to use <code>syncdb</code> without a settings.py, but it requires some advanced knowledge of Django. Of course, you don't need to use <code>syncdb</code>; the tables can be created independently of the models. But it is an aspect of the ORM that is not available unless you put some effort into setup.</p> <p>Secondly, consider how you would create your queries to the DB with the standard <code>Model.objects.filter()</code> call. If this is done as part of a view, it's very simple: construct the <code>QuerySet</code> and view the instances. For example:</p> <pre><code>tag_query = Tag.objects.filter( name='stackoverflow' ) if( tag_query.count() &gt; 0 ): tag = tag_query[0] tag.name = 'stackoverflowed' tag.save() </code></pre> <p>Nice, simple and clean. Now, without the crutch of Django's request/response chaining system, you need to initialise the database connection, make the query, then close the connection. So the above example becomes:</p> <pre><code>from django.db import reset_queries, close_connection, _rollback_on_exception reset_queries() try: tag_query = Tag.objects.filter( name='stackoverflow' ) if( tag_query.count() &gt; 0 ): tag = tag_query[0] tag.name = 'stackoverflowed' tag.save() except: _rollback_on_exception() finally: close_connection() </code></pre> <p>The database connection management can also be done via Django signals. All of the above is defined in <a href="http://code.djangoproject.com/browser/django/trunk/django/db/%5F%5Finit%5F%5F.py">django/db/<strong>init</strong>.py</a>. Other ORMs also have this sort of connection management, but you don't need to dig into their source to find out how to do it. SQL Alchemy's connection management system is documented in the <a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html">tutorials</a> and elsewhere.</p> <p>Finally, you need to keep in mind that the database connection object is local to the current thread at all times, which may or may not limit you depending on your requirements. If your application is not stateless, like Django, but persistent, you may hit threading issues.</p> <p>In conclusion, it is a matter of opinion. In my opinion, both the limitations of, and the setup required for, Django's ORM separate from the framework is too much of a liability. There are perfectly viable dedicated ORM solutions available elsewhere that are designed for library usage. Django's is not. </p> <p>Don't think that all of the above shows I dislike Django and all it's workings, I really do like Django a lot! But I'm realistic about what it's capabilities are and being an ORM library is not one of them.</p> <p>P.S. Multiple database connection support is being <a href="http://code.djangoproject.com/ticket/1142">worked</a> on. But it's not there now.</p>
9
2009-02-23T22:00:22Z
[ "python", "django", "orm" ]
Using only the DB part of Django
579,511
<p>Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables?</p> <p>If not, what would you recommend as "the Python equivalent of Hibernate"?</p>
32
2009-02-23T21:45:54Z
584,208
<p>If you like Django's ORM, it's perfectly simple to use it "standalone"; I've <a href="http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/">written up several techniques for using parts of Django outside of a web context</a>, and you're free to use any of them (or roll your own).</p> <p>Shane above seems to be a bit misinformed on this and a few other points -- for example, Django <em>can</em> do multiple different databases, it just doesn't <em>default</em> to that (you need to do a custom manager on the models which use something other than the "main" DB, something that's not too hard and there are recipes floating around for it). It's true that Django itself doesn't do connection management/connection pooling, but personally I've always used external tools for that anyway (e.g., <code>pgpool</code>, which rocks harder than anything built in to an ORM ever could).</p> <p>I'd suggest spending some time reading up and possibly trying a few likely Google searches (e.g., the post I linked you to comes up as the top result for "standalone Django script") to get a feel for what will actually best suit your needs and tastes -- it may be Django's ORM isn't right for you, and you shouldn't use it if it isn't, but unfortunately there's a lot of misinformation out there which muddies the waters.</p> <p><strong>Editing to respond to Shane:</strong></p> <p>Again, you seem to be misinformed: SQLAlchemy needs to be configured (i.e., told what DB to use, how to connect, etc.) before you can run queries with it, so how is the fact that Django needs similar configuration (accomplished via your choice of methods -- you <strong>do not</strong> need to have a full Django settings file) any disadvantage?</p> <p>As for multiple DB support, you seem to be confused: the support is there at a low level. The query object -- not <code>QuerySet</code>, but the underlying <code>Query</code> object it will execute knows what DB it's connecting to, and accepts a DB connection as one of its initialization arguments. Telling one model to use one DB and another model to use another is as simple as setting up one method on a manager which passes the right connection info down into the <code>Query</code>. True, there's no higher-level API for this, but that's not the same as "no support" and not the same as "requires custom code" (unless you'd argue that configuring multiple DBs explicitly in SQLAlchemy, required if you want multiple DBs, is also "custom code").</p> <p>As for whether you end up <em>indirectly</em> using things that aren't in <code>django.db</code>, well, so what? The fact that <code>django.db</code> imports bits of, say, <code>django.utils</code> because there are data structures and other bits of code which are useful for more than just an ORM is fine as far as I'm personally concerned; one might as well complain if something has external dependencies or makes use of standard Python libraries instead of being 100% self-contained.</p>
72
2009-02-25T00:01:21Z
[ "python", "django", "orm" ]
Using only the DB part of Django
579,511
<p>Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables?</p> <p>If not, what would you recommend as "the Python equivalent of Hibernate"?</p>
32
2009-02-23T21:45:54Z
948,593
<p>(I'm reporting my solution because my question said to be a duplicate)</p> <p>Ah ok I figured it out and will post the solutions for anyone attempting to do the same thing.</p> <p>This solution assumes that you want to create new models.</p> <p>First create a new folder to store your files. We'll call it "standAlone". Within "standAlone", create the following files:</p> <pre><code>__init__.py myScript.py settings.py </code></pre> <p>Obviously "myScript.py" can be named whatever. </p> <p>Next, create a directory for your models.</p> <p>We'll name our model directory "myApp", but realize that this is a normal Django application within a project, as such, name it appropriately to the collection of models you are writing. </p> <p>Within this directory create 2 files: </p> <pre><code>__init__.py models.py </code></pre> <p>Your going to need a copy of manage.py from an either an existing Django project or you can just grab a copy from your Django install path:</p> <pre><code>django\conf\project_template\manage.py </code></pre> <p>Copy the manage.py to your /standAlone directory. Ok so you should now have the following structure:</p> <pre><code>\standAlone __init__.py myScript.py manage.py settings.py \myApp __init__.py models.py </code></pre> <p><strong>Add the following to your myScript.py file:</strong></p> <pre><code># settings.py from django.conf import settings settings.configure( DATABASE_ENGINE = "postgresql_psycopg2", DATABASE_NAME = "myDatabase", DATABASE_USER = "myUsername", DATABASE_PASSWORD = "myPassword", DATABASE_HOST = "localhost", DATABASE_PORT = "5432", INSTALLED_APPS = ("myApp") ) from django.db import models from myApp.models import * </code></pre> <p><strong>and add this to your settings.py file:</strong></p> <pre><code> DATABASE_ENGINE = "postgresql_psycopg2" DATABASE_NAME = "myDatabase" DATABASE_USER = "myUsername" DATABASE_PASSWORD = "myPassword" DATABASE_HOST = "localhost" DATABASE_PORT = "5432", INSTALLED_APPS = ("myApp") </code></pre> <p><strong>and finally your myApp/models.py:</strong></p> <pre><code># myApp/models.py from django.db import models class MyModel(models.Model): field = models.CharField(max_length=255) </code></pre> <p>and that's it. Now to have Django manage your database, in command prompt navigate to our /standalone directory and run: </p> <pre><code>manage.py sql MyApp </code></pre>
6
2009-06-04T04:25:16Z
[ "python", "django", "orm" ]
Using only the DB part of Django
579,511
<p>Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables?</p> <p>If not, what would you recommend as "the Python equivalent of Hibernate"?</p>
32
2009-02-23T21:45:54Z
5,966,125
<p>Take a look at <a href="http://pypi.python.org/pypi/django-standalone" rel="nofollow">django-standalone</a> which makes this setup pretty easy.</p> <p>I also found <a href="http://jystewart.net/2008/02/18/using-the-django-orm-as-a-standalone-component/" rel="nofollow">this blog entry</a> quite useful.</p>
2
2011-05-11T14:43:54Z
[ "python", "django", "orm" ]
Using only the DB part of Django
579,511
<p>Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables?</p> <p>If not, what would you recommend as "the Python equivalent of Hibernate"?</p>
32
2009-02-23T21:45:54Z
20,968,008
<p>I'm using django ORM without a settings file. Here's how: </p> <p>In the stand-alone app launcher file: </p> <pre><code>from django.conf import settings from django.core.management import execute_from_command_line #Django settings settings.configure(DEBUG=False, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/path/to/dbfile', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } }, INSTALLED_APPS = ('modelsapp',) ) if not os.path.exists('/path/to/dbfile'): sync = ['manage.py', 'syncdb'] execute_from_command_line(sync) </code></pre> <p>Now you just need a <code>./modelsapp</code> folder containing an <code>__init__.py</code> and a <code>models.py</code>. The config uses sqlite for simplicity sake, but it could use any of the db backends.</p> <p>Folder structure: </p> <pre><code>./launcher.py ./modelsapp __init__.py models.py </code></pre> <p>Note that you don't have to have a manage.py proper. The <code>import execute_from_command_line</code> just finds it.</p>
2
2014-01-07T09:28:37Z
[ "python", "django", "orm" ]
Using only the DB part of Django
579,511
<p>Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables?</p> <p>If not, what would you recommend as "the Python equivalent of Hibernate"?</p>
32
2009-02-23T21:45:54Z
22,545,158
<p>This example is as simple as it gets. I already have a django app called thab up and running. I want to use the django orm in free standing python scripts and use the same models as I'm using for web programming. Here is an example:</p> <pre><code># nothing in my sys.path contains my django project files import sys sys.path.append('c:\\apython\\thab') # location of django app (module) called thab where my settings.py and models.py is # my settings.py file is actualy in c:\apython\thab\thab from thab import settings as s # need it because my database setting are there dbs = s.DATABASES from django.conf import settings settings.configure(DATABASES=dbs) # configure can only be called once from thab.models import * boards = Board.objects.all() print 'all boards:' + str(boards) # show all the boards in my board table </code></pre>
1
2014-03-20T21:09:57Z
[ "python", "django", "orm" ]
Using only the DB part of Django
579,511
<p>Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables?</p> <p>If not, what would you recommend as "the Python equivalent of Hibernate"?</p>
32
2009-02-23T21:45:54Z
32,492,362
<p>I failed to run <a href="http://stackoverflow.com/a/948593/1145750">KeyboardInterrupt's answer</a> in Django 1.8.For recent <code>Django 1.8</code>, You can have a look at this, in which some parts come from KeyboardInterrupt's answer.</p> <p>The folder structure is:</p> <pre><code>. ├── myApp │   ├── __init__.py │   └── models.py └── my_manage.py </code></pre> <p>myApp is a module, contains an empty <code>__init__.py</code> and <code>models.py</code>.</p> <p>There is an example model class in <code>models.py</code>: from django.db import models</p> <pre><code>class MyModel(models.Model): field = models.CharField(max_length=255) </code></pre> <p>my_manage.py contains django database, installed_app settings and acts as django offical manage.py, so you can:</p> <pre><code>python my_manage.py sql myApp python my_manage.py migrate ...... </code></pre> <p>The codes in <code>my_manage.py</code> are: from django.conf import settings</p> <pre><code>db_conf = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'your_database_name', 'USER': 'your_user_name', 'PASSWORD': 'your_password', 'HOST': 'your_mysql_server_host', 'PORT': 'your_mysql_server_port', } } settings.configure( DATABASES = db_conf, INSTALLED_APPS = ( "myApp", ) ) # Calling django.setup() is required for “standalone” Django u usage # https://docs.djangoproject.com/en/1.8/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage import django django.setup() if __name__ == '__main__': import sys from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) </code></pre>
0
2015-09-10T02:56:27Z
[ "python", "django", "orm" ]
Using only the DB part of Django
579,511
<p>Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables?</p> <p>If not, what would you recommend as "the Python equivalent of Hibernate"?</p>
32
2009-02-23T21:45:54Z
33,218,173
<p>Probably I'm quite late with my answer, but it's better late than never.</p> <p>Try this simple package: <a href="https://github.com/serglopatin/django-models-standalone" rel="nofollow">https://github.com/serglopatin/django-models-standalone</a></p> <p>How to use:</p> <ol> <li><p>download</p></li> <li><p>install</p> <pre><code>python setup.py install </code></pre></li> <li><p>create project</p> <pre><code>django-models-standalone startproject myproject </code></pre></li> <li><p>adjust files settings.py (DATABASES) and models.py, then migrate if tables not created</p></li> <li><p>use djando models in your application (example.py)</p></li> </ol>
0
2015-10-19T15:21:45Z
[ "python", "django", "orm" ]
Using only the DB part of Django
579,511
<p>Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables?</p> <p>If not, what would you recommend as "the Python equivalent of Hibernate"?</p>
32
2009-02-23T21:45:54Z
35,498,794
<pre><code>import django from django.conf import settings from backend_mock.admin import settings as s settings.configure( DATABASES=s.DATABASES, INSTALLED_APPS=('backend_mock.admin.mocker', ) ) django.setup() </code></pre> <p>take a look at this, it's working for django version gte 1.8.x</p>
1
2016-02-19T06:33:55Z
[ "python", "django", "orm" ]
Wrapping objects to extend/add functionality while working around isinstance
579,620
<p>In Python, I've seen the recommendation to use holding or wrapping to extend the functionality of an object or class, rather than inheritance. In particular, I think that Alex Martelli spoke about this in his <a href="http://www.lecturefox.com/blog/python-design-patterns-by-alex-martelli" rel="nofollow">Python Design Patterns</a> talk. I've seen this pattern used in libraries for dependency injection, like <a href="http://pypi.python.org/pypi/PyContainer/0.4" rel="nofollow">pycontainer</a>.</p> <p>One problem that I've run into is that when I have to interface with code that uses the <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns/577848#577848">isinstance anti-pattern</a>, this pattern fails because the holding/wrapping object fails the <code>isinstance</code> test. How can I set up the holding/wrapping object to get around unnecessary type checking? Can this be done generically? In some sense, I need something for class instances analogous to signature-preserving function decorators (e.g., <a href="http://wiki.python.org/moin/PythonDecoratorLibrary" rel="nofollow">simple_decorator</a> or Michele Simionato's <a href="http://pypi.python.org/pypi/decorator" rel="nofollow">decorator</a>).</p> <p>A qualification: I'm not asserting that all <code>isinstance</code> usage is inappropriate; several answers make good points about this. That said, it should be recognized that <code>isinstance</code> usage poses significant limitations on object interactions---it forces <em>inheritance</em> to be the source of polymorphism, rather than <em>behavior</em>.</p> <p>There seems to be some confusion about exactly how/why this is a problem, so let me provide a simple example (broadly lifted from <a href="http://pypi.python.org/pypi/PyContainer/0.4" rel="nofollow">pycontainer</a>). Let's say we have a class Foo, as well as a FooFactory. For the sake of the example, assume we want to be able to instantiate Foo objects that log every function call, or don't---think AOP. Further, we want to do this without modifying the Foo class/source in any way (e.g., we may actually be implementing a generic factory that can add logging ability to any class instance on the fly). A first stab at this might be:</p> <pre><code>class Foo(object): def bar(): print 'We\'re out of Red Leicester.' class LogWrapped(object): def __init__(self, wrapped): self.wrapped = wrapped def __getattr__(self, name): attr = getattr(self.wrapped, name) if not callable(attr): return attr else: def fun(*args, **kwargs): print 'Calling ', name attr(*args, **kwargs) print 'Called ', name return fun class FooFactory(object): def get_foo(with_logging = False): if not with_logging: return Foo() else: return LogWrapped(Foo()) foo_fact = FooFactory() my_foo = foo_fact.get_foo(True) isinstance(my_foo, Foo) # False! </code></pre> <p>There are may reasons why you might want to do things exactly this way (use decorators instead, etc.) but keep in mind:</p> <ul> <li>We don't want to touch the Foo class. Assume we're writing framework code that could be used by clients we don't know about yet.</li> <li>The point is to return an object that is essentially a Foo, but with added functionality. It should appear to be a Foo---as much as possible---to any other client code expecting a Foo. Hence the desire to work around <code>isinstance</code>.</li> <li>Yes, I know that I don't need the factory class (preemptively defending myself here). </li> </ul>
5
2009-02-23T22:17:28Z
579,683
<ul> <li><p>Python 2.6 has the class-level decorators you desire. <a href="http://docs.python.org/3.0/whatsnew/2.6.html#pep-3129-class-decorators" rel="nofollow">http://docs.python.org/3.0/whatsnew/2.6.html#pep-3129-class-decorators</a></p></li> <li><p>You could maybe use Metaclasses: <a href="http://www.google.com/search?q=python+metaclasses" rel="nofollow">http://www.google.com/search?q=python+metaclasses</a> (this way lies madness). I'm not sure it would completely solve your problem, but it might be fun trying. ;-)</p></li> </ul>
0
2009-02-23T22:37:25Z
[ "python", "design-patterns" ]
Wrapping objects to extend/add functionality while working around isinstance
579,620
<p>In Python, I've seen the recommendation to use holding or wrapping to extend the functionality of an object or class, rather than inheritance. In particular, I think that Alex Martelli spoke about this in his <a href="http://www.lecturefox.com/blog/python-design-patterns-by-alex-martelli" rel="nofollow">Python Design Patterns</a> talk. I've seen this pattern used in libraries for dependency injection, like <a href="http://pypi.python.org/pypi/PyContainer/0.4" rel="nofollow">pycontainer</a>.</p> <p>One problem that I've run into is that when I have to interface with code that uses the <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns/577848#577848">isinstance anti-pattern</a>, this pattern fails because the holding/wrapping object fails the <code>isinstance</code> test. How can I set up the holding/wrapping object to get around unnecessary type checking? Can this be done generically? In some sense, I need something for class instances analogous to signature-preserving function decorators (e.g., <a href="http://wiki.python.org/moin/PythonDecoratorLibrary" rel="nofollow">simple_decorator</a> or Michele Simionato's <a href="http://pypi.python.org/pypi/decorator" rel="nofollow">decorator</a>).</p> <p>A qualification: I'm not asserting that all <code>isinstance</code> usage is inappropriate; several answers make good points about this. That said, it should be recognized that <code>isinstance</code> usage poses significant limitations on object interactions---it forces <em>inheritance</em> to be the source of polymorphism, rather than <em>behavior</em>.</p> <p>There seems to be some confusion about exactly how/why this is a problem, so let me provide a simple example (broadly lifted from <a href="http://pypi.python.org/pypi/PyContainer/0.4" rel="nofollow">pycontainer</a>). Let's say we have a class Foo, as well as a FooFactory. For the sake of the example, assume we want to be able to instantiate Foo objects that log every function call, or don't---think AOP. Further, we want to do this without modifying the Foo class/source in any way (e.g., we may actually be implementing a generic factory that can add logging ability to any class instance on the fly). A first stab at this might be:</p> <pre><code>class Foo(object): def bar(): print 'We\'re out of Red Leicester.' class LogWrapped(object): def __init__(self, wrapped): self.wrapped = wrapped def __getattr__(self, name): attr = getattr(self.wrapped, name) if not callable(attr): return attr else: def fun(*args, **kwargs): print 'Calling ', name attr(*args, **kwargs) print 'Called ', name return fun class FooFactory(object): def get_foo(with_logging = False): if not with_logging: return Foo() else: return LogWrapped(Foo()) foo_fact = FooFactory() my_foo = foo_fact.get_foo(True) isinstance(my_foo, Foo) # False! </code></pre> <p>There are may reasons why you might want to do things exactly this way (use decorators instead, etc.) but keep in mind:</p> <ul> <li>We don't want to touch the Foo class. Assume we're writing framework code that could be used by clients we don't know about yet.</li> <li>The point is to return an object that is essentially a Foo, but with added functionality. It should appear to be a Foo---as much as possible---to any other client code expecting a Foo. Hence the desire to work around <code>isinstance</code>.</li> <li>Yes, I know that I don't need the factory class (preemptively defending myself here). </li> </ul>
5
2009-02-23T22:17:28Z
579,986
<p>My first impulse would be to try to fix the offending code which uses <code>isinstance</code>. Otherwise you're just propagating its design mistakes in to your own design. Any reason you can't modify it?</p> <p><strong>Edit:</strong> So your justification is that you're writing framework/library code that you want people to be able to use in all cases, even if they want to use isinstance?</p> <p>I think there's several things wrong with this:</p> <ul> <li>You're trying to support a broken paradigm</li> <li>You're the one defining the library and its interfaces, it's up to the users to use it properly.</li> <li>There's no way you can possibly anticipate all the bad programming your library users will do, so it's pretty much a futile effort to try to support bad programming practices</li> </ul> <p>I think you're best off writing idiomatic, well designed code. Good code (and bad code) has a tendency to spread, so make yours an example. Hopefully it will lead to an overall increase in code quality. Going the other way will only continue the quality decline.</p>
0
2009-02-24T00:24:11Z
[ "python", "design-patterns" ]
Wrapping objects to extend/add functionality while working around isinstance
579,620
<p>In Python, I've seen the recommendation to use holding or wrapping to extend the functionality of an object or class, rather than inheritance. In particular, I think that Alex Martelli spoke about this in his <a href="http://www.lecturefox.com/blog/python-design-patterns-by-alex-martelli" rel="nofollow">Python Design Patterns</a> talk. I've seen this pattern used in libraries for dependency injection, like <a href="http://pypi.python.org/pypi/PyContainer/0.4" rel="nofollow">pycontainer</a>.</p> <p>One problem that I've run into is that when I have to interface with code that uses the <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns/577848#577848">isinstance anti-pattern</a>, this pattern fails because the holding/wrapping object fails the <code>isinstance</code> test. How can I set up the holding/wrapping object to get around unnecessary type checking? Can this be done generically? In some sense, I need something for class instances analogous to signature-preserving function decorators (e.g., <a href="http://wiki.python.org/moin/PythonDecoratorLibrary" rel="nofollow">simple_decorator</a> or Michele Simionato's <a href="http://pypi.python.org/pypi/decorator" rel="nofollow">decorator</a>).</p> <p>A qualification: I'm not asserting that all <code>isinstance</code> usage is inappropriate; several answers make good points about this. That said, it should be recognized that <code>isinstance</code> usage poses significant limitations on object interactions---it forces <em>inheritance</em> to be the source of polymorphism, rather than <em>behavior</em>.</p> <p>There seems to be some confusion about exactly how/why this is a problem, so let me provide a simple example (broadly lifted from <a href="http://pypi.python.org/pypi/PyContainer/0.4" rel="nofollow">pycontainer</a>). Let's say we have a class Foo, as well as a FooFactory. For the sake of the example, assume we want to be able to instantiate Foo objects that log every function call, or don't---think AOP. Further, we want to do this without modifying the Foo class/source in any way (e.g., we may actually be implementing a generic factory that can add logging ability to any class instance on the fly). A first stab at this might be:</p> <pre><code>class Foo(object): def bar(): print 'We\'re out of Red Leicester.' class LogWrapped(object): def __init__(self, wrapped): self.wrapped = wrapped def __getattr__(self, name): attr = getattr(self.wrapped, name) if not callable(attr): return attr else: def fun(*args, **kwargs): print 'Calling ', name attr(*args, **kwargs) print 'Called ', name return fun class FooFactory(object): def get_foo(with_logging = False): if not with_logging: return Foo() else: return LogWrapped(Foo()) foo_fact = FooFactory() my_foo = foo_fact.get_foo(True) isinstance(my_foo, Foo) # False! </code></pre> <p>There are may reasons why you might want to do things exactly this way (use decorators instead, etc.) but keep in mind:</p> <ul> <li>We don't want to touch the Foo class. Assume we're writing framework code that could be used by clients we don't know about yet.</li> <li>The point is to return an object that is essentially a Foo, but with added functionality. It should appear to be a Foo---as much as possible---to any other client code expecting a Foo. Hence the desire to work around <code>isinstance</code>.</li> <li>Yes, I know that I don't need the factory class (preemptively defending myself here). </li> </ul>
5
2009-02-23T22:17:28Z
581,263
<p>If the library code you depend on uses <code>isinstance</code> and relies on inheritance why not follow this route? If you cannot change the library then it is probably best to stay consistend with it.</p> <p>I also think that there are legitimate uses for <code>isinstance</code>, and with the introduction of <a href="http://www.python.org/dev/peps/pep-3119/" rel="nofollow">abstract base classes</a> in 2.6 this has been officially acknowledged. There are situations where <code>isinstance</code> really is the right solution, as opposed to duck typing with <code>hasattr</code> or using exceptions.</p> <p>Some dirty options if for some reason you really don't want to use inheritance:</p> <ul> <li>You could modify only the class instances by using instance methods. With <code>new.instancemethod</code> you create the wrapper methods for your instance, which then calls the original method defined in the original class. This seems to be the only option which neither modifies the original class nor defines new classes.</li> </ul> <p>If you can modify the class at runtime there are many options:</p> <ul> <li><p>Use a runtime mixin, i.e. just add a class to the <code>__base__</code> attribute of your class. But this is more used for adding specific functionality, not for indiscriminate wrapping where you don't know what need to be wrapped.</p></li> <li><p>The options in Dave's answer (class decorators in Python >= 2.6 or Metaclasses).</p></li> </ul> <p>Edit: For your specific example I guess only the first option works. But I would still consider the alternative of creating a <code>LogFoo</code> or chosing an altogether different solution for something specific like logging.</p>
2
2009-02-24T10:35:52Z
[ "python", "design-patterns" ]
Wrapping objects to extend/add functionality while working around isinstance
579,620
<p>In Python, I've seen the recommendation to use holding or wrapping to extend the functionality of an object or class, rather than inheritance. In particular, I think that Alex Martelli spoke about this in his <a href="http://www.lecturefox.com/blog/python-design-patterns-by-alex-martelli" rel="nofollow">Python Design Patterns</a> talk. I've seen this pattern used in libraries for dependency injection, like <a href="http://pypi.python.org/pypi/PyContainer/0.4" rel="nofollow">pycontainer</a>.</p> <p>One problem that I've run into is that when I have to interface with code that uses the <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns/577848#577848">isinstance anti-pattern</a>, this pattern fails because the holding/wrapping object fails the <code>isinstance</code> test. How can I set up the holding/wrapping object to get around unnecessary type checking? Can this be done generically? In some sense, I need something for class instances analogous to signature-preserving function decorators (e.g., <a href="http://wiki.python.org/moin/PythonDecoratorLibrary" rel="nofollow">simple_decorator</a> or Michele Simionato's <a href="http://pypi.python.org/pypi/decorator" rel="nofollow">decorator</a>).</p> <p>A qualification: I'm not asserting that all <code>isinstance</code> usage is inappropriate; several answers make good points about this. That said, it should be recognized that <code>isinstance</code> usage poses significant limitations on object interactions---it forces <em>inheritance</em> to be the source of polymorphism, rather than <em>behavior</em>.</p> <p>There seems to be some confusion about exactly how/why this is a problem, so let me provide a simple example (broadly lifted from <a href="http://pypi.python.org/pypi/PyContainer/0.4" rel="nofollow">pycontainer</a>). Let's say we have a class Foo, as well as a FooFactory. For the sake of the example, assume we want to be able to instantiate Foo objects that log every function call, or don't---think AOP. Further, we want to do this without modifying the Foo class/source in any way (e.g., we may actually be implementing a generic factory that can add logging ability to any class instance on the fly). A first stab at this might be:</p> <pre><code>class Foo(object): def bar(): print 'We\'re out of Red Leicester.' class LogWrapped(object): def __init__(self, wrapped): self.wrapped = wrapped def __getattr__(self, name): attr = getattr(self.wrapped, name) if not callable(attr): return attr else: def fun(*args, **kwargs): print 'Calling ', name attr(*args, **kwargs) print 'Called ', name return fun class FooFactory(object): def get_foo(with_logging = False): if not with_logging: return Foo() else: return LogWrapped(Foo()) foo_fact = FooFactory() my_foo = foo_fact.get_foo(True) isinstance(my_foo, Foo) # False! </code></pre> <p>There are may reasons why you might want to do things exactly this way (use decorators instead, etc.) but keep in mind:</p> <ul> <li>We don't want to touch the Foo class. Assume we're writing framework code that could be used by clients we don't know about yet.</li> <li>The point is to return an object that is essentially a Foo, but with added functionality. It should appear to be a Foo---as much as possible---to any other client code expecting a Foo. Hence the desire to work around <code>isinstance</code>.</li> <li>Yes, I know that I don't need the factory class (preemptively defending myself here). </li> </ul>
5
2009-02-23T22:17:28Z
582,898
<p>One thing to keep in mind is that you don't necessarily have to <em>use</em> anything in a base class if you go the inheritance route. You can make a stub class to inherit from that doesn't add any concrete implementation. I've done something like this several times:</p> <pre><code>class Message(object): pass class ClassToBeWrapped(object): #... class MessageWithConcreteImplementation(Message): def __init__(self): self.x = ClassToBeWrapped() #... add concrete implementation here x = MessageWithConcreteImplementation() isinstance(x, Message) </code></pre> <p>If you need to inherit from other things, I suppose you could run into some problems with multiple inheritance, but this should be fairly minimal if you don't provide any concrete implementation.</p> <blockquote> <p>One problem that I've run into is that when I have to interface with code that uses the isinstance anti-pattern</p> </blockquote> <p>I agree that isinstance is to be avoided if possible, but I'm not sure I'd call it an antipattern. There are some valid reasons to use isinstance. For instance, there are some message passing frameworks that use this to define messages. For example, if you get a class that inherits from Shutdown, it's time for a subsystem to shut down.</p>
1
2009-02-24T18:17:58Z
[ "python", "design-patterns" ]
Wrapping objects to extend/add functionality while working around isinstance
579,620
<p>In Python, I've seen the recommendation to use holding or wrapping to extend the functionality of an object or class, rather than inheritance. In particular, I think that Alex Martelli spoke about this in his <a href="http://www.lecturefox.com/blog/python-design-patterns-by-alex-martelli" rel="nofollow">Python Design Patterns</a> talk. I've seen this pattern used in libraries for dependency injection, like <a href="http://pypi.python.org/pypi/PyContainer/0.4" rel="nofollow">pycontainer</a>.</p> <p>One problem that I've run into is that when I have to interface with code that uses the <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns/577848#577848">isinstance anti-pattern</a>, this pattern fails because the holding/wrapping object fails the <code>isinstance</code> test. How can I set up the holding/wrapping object to get around unnecessary type checking? Can this be done generically? In some sense, I need something for class instances analogous to signature-preserving function decorators (e.g., <a href="http://wiki.python.org/moin/PythonDecoratorLibrary" rel="nofollow">simple_decorator</a> or Michele Simionato's <a href="http://pypi.python.org/pypi/decorator" rel="nofollow">decorator</a>).</p> <p>A qualification: I'm not asserting that all <code>isinstance</code> usage is inappropriate; several answers make good points about this. That said, it should be recognized that <code>isinstance</code> usage poses significant limitations on object interactions---it forces <em>inheritance</em> to be the source of polymorphism, rather than <em>behavior</em>.</p> <p>There seems to be some confusion about exactly how/why this is a problem, so let me provide a simple example (broadly lifted from <a href="http://pypi.python.org/pypi/PyContainer/0.4" rel="nofollow">pycontainer</a>). Let's say we have a class Foo, as well as a FooFactory. For the sake of the example, assume we want to be able to instantiate Foo objects that log every function call, or don't---think AOP. Further, we want to do this without modifying the Foo class/source in any way (e.g., we may actually be implementing a generic factory that can add logging ability to any class instance on the fly). A first stab at this might be:</p> <pre><code>class Foo(object): def bar(): print 'We\'re out of Red Leicester.' class LogWrapped(object): def __init__(self, wrapped): self.wrapped = wrapped def __getattr__(self, name): attr = getattr(self.wrapped, name) if not callable(attr): return attr else: def fun(*args, **kwargs): print 'Calling ', name attr(*args, **kwargs) print 'Called ', name return fun class FooFactory(object): def get_foo(with_logging = False): if not with_logging: return Foo() else: return LogWrapped(Foo()) foo_fact = FooFactory() my_foo = foo_fact.get_foo(True) isinstance(my_foo, Foo) # False! </code></pre> <p>There are may reasons why you might want to do things exactly this way (use decorators instead, etc.) but keep in mind:</p> <ul> <li>We don't want to touch the Foo class. Assume we're writing framework code that could be used by clients we don't know about yet.</li> <li>The point is to return an object that is essentially a Foo, but with added functionality. It should appear to be a Foo---as much as possible---to any other client code expecting a Foo. Hence the desire to work around <code>isinstance</code>.</li> <li>Yes, I know that I don't need the factory class (preemptively defending myself here). </li> </ul>
5
2009-02-23T22:17:28Z
583,024
<p>If you're writing a framework that needs to accept some sort of inputs from your API users, then there's no reason I can think of to use isinstance. Ugly as it might be, I always just check to see if it actually provides the interface I mean to use:</p> <pre><code>def foo(bar): if hasattr(bar, "baz") and hasattr(bar, "quux"): twiddle(bar.baz, bar.quux()) elif hasattr(bar, "quuux"): etc... </code></pre> <p>And I also often provide a nice class to inherit default functionality, if the API user wants to use it:</p> <pre><code>class Bar: def baz(self): return self.quux("glu") def quux(self): raise NotImplemented </code></pre>
0
2009-02-24T18:46:09Z
[ "python", "design-patterns" ]
How do I copy a string to the clipboard on Windows using Python?
579,687
<p>I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?</p>
123
2009-02-23T22:38:02Z
579,715
<p>Looks like you need to add win32clipboard to your site-packages. It's part of the <a href="http://sourceforge.net/projects/pywin32/">pywin32 package</a></p>
10
2009-02-23T22:43:08Z
[ "python", "clipboard" ]
How do I copy a string to the clipboard on Windows using Python?
579,687
<p>I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?</p>
123
2009-02-23T22:38:02Z
3,429,034
<p>You can also use ctypes to tap into the windows API and avoid the massive pywin32 package. This is what I use, (excuse the poor style, but the idea is there.) </p> <pre><code>import ctypes #Get required functions, strcpy.. strcpy = ctypes.cdll.msvcrt.strcpy ocb = ctypes.windll.user32.OpenClipboard #Basic Clipboard functions ecb = ctypes.windll.user32.EmptyClipboard gcd = ctypes.windll.user32.GetClipboardData scd = ctypes.windll.user32.SetClipboardData ccb = ctypes.windll.user32.CloseClipboard ga = ctypes.windll.kernel32.GlobalAlloc # Global Memory allocation gl = ctypes.windll.kernel32.GlobalLock # Global Memory Locking gul = ctypes.windll.kernel32.GlobalUnlock GMEM_DDESHARE = 0x2000 def Get( ): ocb(None) # Open Clip, Default task pcontents = gcd(1) # 1 means CF_TEXT.. too lazy to get the token thingy ... data = ctypes.c_char_p(pcontents).value #gul(pcontents) ? ccb() return data def Paste( data ): ocb(None) # Open Clip, Default task ecb() hCd = ga( GMEM_DDESHARE, len( bytes(data,"ascii") )+1 ) pchData = gl(hCd) strcpy(ctypes.c_char_p(pchData),bytes(data,"ascii")) gul(hCd) scd(1,hCd) ccb() </code></pre>
22
2010-08-07T03:33:26Z
[ "python", "clipboard" ]
How do I copy a string to the clipboard on Windows using Python?
579,687
<p>I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?</p>
123
2009-02-23T22:38:02Z
4,203,897
<p>Actually, <code>pywin32</code> and <code>ctypes</code> seem to be an overkill for this simple task. <code>Tkinter</code> is a cross-platform GUI framework, which ships with Python by default and has clipboard accessing methods along with other cool stuff.</p> <p>If all you need is to put some text to system clipboard, this will do it:</p> <pre><code>from Tkinter import Tk r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append('i can has clipboardz?') r.destroy() </code></pre> <p>And that's all, no need to mess around with platform-specific third-party libraries.</p>
196
2010-11-17T11:31:06Z
[ "python", "clipboard" ]
How do I copy a string to the clipboard on Windows using Python?
579,687
<p>I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?</p>
123
2009-02-23T22:38:02Z
9,409,898
<p>I didn't have a solution just a work around</p> <p>Windows vista onwards has an inbuilt command called clip that takes the output of a command from command line and puts it into the clipboard. E.g. ipconfig | clip </p> <p>So i made a function with the os module which takes the string and adds it to the clipboard using the inbuilt windows solution. </p> <pre><code>import os def addToClipBoard(text): command = 'echo ' + text.strip() + '| clip' os.system(command) #example addToClipBoard('penny lane') #Penny Lane is now in your ears,eyes and clipboard </code></pre> <p>If you are using windows XP it will work just follow the steps on this site first. </p> <p><a href="http://www.techrepublic.com/blog/window-on-windows/copy-and-paste-from-windows-xp-pros-command-prompt-straight-to-the-clipboard/521">http://www.techrepublic.com/blog/window-on-windows/copy-and-paste-from-windows-xp-pros-command-prompt-straight-to-the-clipboard/521</a></p>
53
2012-02-23T09:06:00Z
[ "python", "clipboard" ]
How do I copy a string to the clipboard on Windows using Python?
579,687
<p>I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?</p>
123
2009-02-23T22:38:02Z
19,602,654
<p>Widgets also have method named <code>.clipboard_get()</code> that returns the contents of the clipboard (unless some kind of error happens based on the type of data in the clipboard).</p> <p>The <code>clipboard_get()</code> method is mentioned in this bug report:<br> <a href="http://bugs.python.org/issue14777" rel="nofollow">http://bugs.python.org/issue14777</a></p> <p>Strangely, this method was not mentioned in the common (but unofficial) online TkInter documentation sources that I usually refer to.</p>
2
2013-10-26T04:00:27Z
[ "python", "clipboard" ]
How do I copy a string to the clipboard on Windows using Python?
579,687
<p>I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?</p>
123
2009-02-23T22:38:02Z
24,523,659
<p>You can use <a href="http://coffeeghost.net/2010/10/09/pyperclip-a-cross-platform-clipboard-module-for-python/"><strong>pyperclip</strong></a> - cross-platform clipboard module. Or <a href="https://github.com/kennethreitz/xerox"><strong>Xerox</strong></a> - similar module, except requires the win32 Python module to work on Windows.</p>
17
2014-07-02T05:43:27Z
[ "python", "clipboard" ]
How do I copy a string to the clipboard on Windows using Python?
579,687
<p>I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?</p>
123
2009-02-23T22:38:02Z
24,919,985
<pre><code>from Tkinter import Tk clip = Tk() </code></pre>
-7
2014-07-23T20:07:59Z
[ "python", "clipboard" ]
How do I copy a string to the clipboard on Windows using Python?
579,687
<p>I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?</p>
123
2009-02-23T22:38:02Z
25,678,113
<p>For some reason I've never been able to get the Tk solution to work for me. <a href="http://stackoverflow.com/a/3429034/5987">kapace's solution</a> is much more workable, but the formatting is contrary to my style and it doesn't work with Unicode. Here's a modified version.</p> <pre><code>import ctypes OpenClipboard = ctypes.windll.user32.OpenClipboard EmptyClipboard = ctypes.windll.user32.EmptyClipboard GetClipboardData = ctypes.windll.user32.GetClipboardData SetClipboardData = ctypes.windll.user32.SetClipboardData CloseClipboard = ctypes.windll.user32.CloseClipboard CF_UNICODETEXT = 13 GlobalAlloc = ctypes.windll.kernel32.GlobalAlloc GlobalLock = ctypes.windll.kernel32.GlobalLock GlobalUnlock = ctypes.windll.kernel32.GlobalUnlock GlobalSize = ctypes.windll.kernel32.GlobalSize GMEM_MOVEABLE = 0x0002 GMEM_ZEROINIT = 0x0040 unicode_type = type(u'') def get(): text = None OpenClipboard(None) handle = GetClipboardData(CF_UNICODETEXT) pcontents = GlobalLock(handle) size = GlobalSize(handle) if pcontents and size: raw_data = ctypes.create_string_buffer(size) ctypes.memmove(raw_data, pcontents, size) text = raw_data.raw.decode('utf-16le').rstrip(u'\0') GlobalUnlock(handle) CloseClipboard() return text def put(s): if not isinstance(s, unicode_type): s = s.decode('mbcs') data = s.encode('utf-16le') OpenClipboard(None) EmptyClipboard() handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, len(data) + 2) pcontents = GlobalLock(handle) ctypes.memmove(pcontents, data, len(data)) GlobalUnlock(handle) SetClipboardData(CF_UNICODETEXT, handle) CloseClipboard() paste = get copy = put </code></pre> <p>The above has changed since this answer was first created, to better cope with extended Unicode characters and Python 3. It has been tested in both Python 2.7 and 3.5, and works even with emoji such as <code>\U0001f601 (😁)</code>.</p>
3
2014-09-05T03:11:03Z
[ "python", "clipboard" ]
How do I copy a string to the clipboard on Windows using Python?
579,687
<p>I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?</p>
123
2009-02-23T22:38:02Z
27,291,478
<p>I've tried various solutions, but this is the simplest one that passes <a href="https://gist.github.com/CTimmerman/133cb80100357dde92d8" rel="nofollow">my test</a>:</p> <pre><code>#coding=utf-8 import win32clipboard # http://sourceforge.net/projects/pywin32/ def copy(text): win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(text, win32clipboard.CF_UNICODETEXT) win32clipboard.CloseClipboard() def paste(): win32clipboard.OpenClipboard() data = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT) win32clipboard.CloseClipboard() return data if __name__ == "__main__": text = "Testing\nthe “clip—board”: 📋" try: text = text.decode('utf8') # Python 2 needs decode to make a Unicode string. except AttributeError: pass print("%r" % text.encode('utf8')) copy(text) data = paste() print("%r" % data.encode('utf8')) print("OK" if text == data else "FAIL") try: print(data) except UnicodeEncodeError as er: print(er) print(data.encode('utf8')) </code></pre> <p>Tested OK in Python 3.4 on Windows 8.1 and Python 2.7 on Windows 7. Also when reading Unicode data with Unix linefeeds copied from Windows. Copied data stays on the clipboard after Python exits: <code>"Testing the “clip—board”: 📋"</code></p> <p>If you want no external dependencies, use this code (now part of cross-platform <code>pyperclip</code> - <code>C:\Python34\Scripts\pip install --upgrade pyperclip</code>):</p> <pre><code>def copy(text): GMEM_DDESHARE = 0x2000 CF_UNICODETEXT = 13 d = ctypes.windll # cdll expects 4 more bytes in user32.OpenClipboard(None) try: # Python 2 if not isinstance(text, unicode): text = text.decode('mbcs') except NameError: if not isinstance(text, str): text = text.decode('mbcs') d.user32.OpenClipboard(0) d.user32.EmptyClipboard() hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2) pchData = d.kernel32.GlobalLock(hCd) ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text) d.kernel32.GlobalUnlock(hCd) d.user32.SetClipboardData(CF_UNICODETEXT, hCd) d.user32.CloseClipboard() def paste(): CF_UNICODETEXT = 13 d = ctypes.windll d.user32.OpenClipboard(0) handle = d.user32.GetClipboardData(CF_UNICODETEXT) text = ctypes.c_wchar_p(handle).value d.user32.CloseClipboard() return text </code></pre>
4
2014-12-04T10:20:38Z
[ "python", "clipboard" ]
How do I copy a string to the clipboard on Windows using Python?
579,687
<p>I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?</p>
123
2009-02-23T22:38:02Z
29,632,881
<pre><code>import wx def ctc(text): if not wx.TheClipboard.IsOpened(): wx.TheClipboard.Open() data = wx.TextDataObject() data.SetText(text) wx.TheClipboard.SetData(data) wx.TheClipboard.Close() ctc(text) </code></pre>
0
2015-04-14T16:41:37Z
[ "python", "clipboard" ]
How do I copy a string to the clipboard on Windows using Python?
579,687
<p>I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?</p>
123
2009-02-23T22:38:02Z
33,540,623
<p>Code snippet to copy clipboard</p> <p>Create a wrapper python code in a module named (<em>clipboard.py</em>)</p> <pre><code>import clr clr.AddReference('System.Windows.Forms') from System.Windows.Forms import Clipboard def setText(text): Clipboard.SetText(text) def getText(): return Clipboard.GetText() </code></pre> <p>Then import the above module into your code</p> <pre><code>import io import clipboard code = clipboard.getText() print code code = "abcd" clipboard.setText(code) </code></pre> <p>I must give credit to the site <a href="http://mark-dot-net.blogspot.nl/2010/10/clipboard-access-in-ironpython.html" rel="nofollow">http://mark-dot-net.blogspot.nl/2010/10/clipboard-access-in-ironpython.html</a></p>
-1
2015-11-05T09:19:09Z
[ "python", "clipboard" ]
How do I copy a string to the clipboard on Windows using Python?
579,687
<p>I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?</p>
123
2009-02-23T22:38:02Z
36,178,407
<p>You can use the excellent pandas, which has a built in clipboard support, but you need to pass through a DataFrame.</p> <pre><code>import pandas as pd df=pd.DataFrame(['Text to copy']) df.to_clipboard(index=False,header=False) </code></pre>
1
2016-03-23T12:36:54Z
[ "python", "clipboard" ]
Python ORM that auto-generates/updates tables and uses SQLite?
579,770
<p>I am doing some prototyping for a new desktop app i am writing in Python, and i want to use SQLite and an ORM to store data.</p> <p>My question is, are there any ORM libraries that support auto-generating/updating the database schema and work with SQLite?</p>
9
2009-02-23T22:59:10Z
579,787
<p><a href="http://www.sqlalchemy.org/">SQLAlchemy</a> is a great choice in the Python ORM space that supports SQLite.</p>
16
2009-02-23T23:05:02Z
[ "python", "sqlite", "orm", "auto-generate" ]
Python ORM that auto-generates/updates tables and uses SQLite?
579,770
<p>I am doing some prototyping for a new desktop app i am writing in Python, and i want to use SQLite and an ORM to store data.</p> <p>My question is, are there any ORM libraries that support auto-generating/updating the database schema and work with SQLite?</p>
9
2009-02-23T22:59:10Z
580,219
<p>SQLAlchemy, when used with the <a href="http://code.google.com/p/sqlalchemy-migrate/" rel="nofollow">sqlalchemy-migrate</a> library.</p>
2
2009-02-24T02:18:30Z
[ "python", "sqlite", "orm", "auto-generate" ]
Change basic (immutable) types inside a function in Python?
579,782
<p>I am using a C++ SDK where there is a function like (it has a python wrapper, but not docs):</p> <pre><code>getPos ( int uvId, float &amp; u, float &amp; v ) const </code></pre> <p>How do I specify in Python so that the passed variables are changed?</p> <p>I tried this example to see if I could modify floats inside a function, but it didn't work, so printed 12.0:</p> <pre><code>def change ( a ) : a = 35.0 b = 12.0 change ( b ) print b </code></pre> <p>So how do I call this function that I can change 2 external floats in Python?</p> <p>Related:</p> <ul> <li><a href="http://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls/">Python: variable scope and function calls</a></li> </ul>
0
2009-02-23T23:03:12Z
579,788
<p>For simple cases have the function return the new value.</p> <p>For more complicated cases you can pass in a object or a list and have that changed:</p> <pre><code>def foobar(alist): alist[0] = 10 blist = [42] foobar(blist) print blist[0] </code></pre> <p>Edit:</p> <p>For wrapping C++ references there isn't any standard way (basic python interfaces are at the C level - not C++) - so it depends how the python interface has been implemented - it might be arrays, or returning multiple values. I'm not sure how boost.python handles it but you might start there, or maybe look under a debugger to see how the parameter are handled.</p>
0
2009-02-23T23:05:20Z
[ "python", "variables", "pass-by-reference" ]
Change basic (immutable) types inside a function in Python?
579,782
<p>I am using a C++ SDK where there is a function like (it has a python wrapper, but not docs):</p> <pre><code>getPos ( int uvId, float &amp; u, float &amp; v ) const </code></pre> <p>How do I specify in Python so that the passed variables are changed?</p> <p>I tried this example to see if I could modify floats inside a function, but it didn't work, so printed 12.0:</p> <pre><code>def change ( a ) : a = 35.0 b = 12.0 change ( b ) print b </code></pre> <p>So how do I call this function that I can change 2 external floats in Python?</p> <p>Related:</p> <ul> <li><a href="http://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls/">Python: variable scope and function calls</a></li> </ul>
0
2009-02-23T23:03:12Z
579,805
<p>In Python:</p> <pre><code>def getPos(uvID): # compute u, v return u, v # u, v = getPos(uvID) </code></pre>
5
2009-02-23T23:11:23Z
[ "python", "variables", "pass-by-reference" ]
Change basic (immutable) types inside a function in Python?
579,782
<p>I am using a C++ SDK where there is a function like (it has a python wrapper, but not docs):</p> <pre><code>getPos ( int uvId, float &amp; u, float &amp; v ) const </code></pre> <p>How do I specify in Python so that the passed variables are changed?</p> <p>I tried this example to see if I could modify floats inside a function, but it didn't work, so printed 12.0:</p> <pre><code>def change ( a ) : a = 35.0 b = 12.0 change ( b ) print b </code></pre> <p>So how do I call this function that I can change 2 external floats in Python?</p> <p>Related:</p> <ul> <li><a href="http://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls/">Python: variable scope and function calls</a></li> </ul>
0
2009-02-23T23:03:12Z
579,817
<p>As far I know, Python doesn't support call-by-reference, so the exact code you are suggesting doesn't work (obviously).</p> <p>The tool (or person) that generated the Python wrapper for the C++ function must have done something special to support this function (hopefully, or you won't be able to use it). Do you know what tool was used to generate the wrapper?</p> <p>Usually tools like this will generate some sort of container data type:</p> <pre><code>b.value = 12.0 change(b) print b.value </code></pre>
2
2009-02-23T23:16:00Z
[ "python", "variables", "pass-by-reference" ]
Change basic (immutable) types inside a function in Python?
579,782
<p>I am using a C++ SDK where there is a function like (it has a python wrapper, but not docs):</p> <pre><code>getPos ( int uvId, float &amp; u, float &amp; v ) const </code></pre> <p>How do I specify in Python so that the passed variables are changed?</p> <p>I tried this example to see if I could modify floats inside a function, but it didn't work, so printed 12.0:</p> <pre><code>def change ( a ) : a = 35.0 b = 12.0 change ( b ) print b </code></pre> <p>So how do I call this function that I can change 2 external floats in Python?</p> <p>Related:</p> <ul> <li><a href="http://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls/">Python: variable scope and function calls</a></li> </ul>
0
2009-02-23T23:03:12Z
580,024
<p>You're going to have to resort to <a href="https://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a>.</p> <p>Specifically, see <a href="https://docs.python.org/library/ctypes.html#passing-pointers-or-passing-parameters-by-reference" rel="nofollow">https://docs.python.org/library/ctypes.html#passing-pointers-or-passing-parameters-by-reference</a></p>
2
2009-02-24T00:38:15Z
[ "python", "variables", "pass-by-reference" ]
What's the Pythonic way to combine two sequences into a dictionary?
579,856
<p>Is there a more concise way of doing this in Python?:</p> <pre><code>def toDict(keys, values): d = dict() for k,v in zip(keys, values): d[k] = v return d </code></pre>
7
2009-02-23T23:33:26Z
579,862
<p>Yes:</p> <pre><code>dict(zip(keys,values)) </code></pre>
42
2009-02-23T23:35:34Z
[ "python" ]
What's the Pythonic way to combine two sequences into a dictionary?
579,856
<p>Is there a more concise way of doing this in Python?:</p> <pre><code>def toDict(keys, values): d = dict() for k,v in zip(keys, values): d[k] = v return d </code></pre>
7
2009-02-23T23:33:26Z
579,928
<p>If <code>keys</code>' size may be larger then <code>values</code>' one then you could use <a href="http://docs.python.org/library/itertools.html#itertools.izip_longest" rel="nofollow"><code>itertools.izip_longest</code></a> (Python 2.6) which allows to specify a default value for the rest of the keys:</p> <pre><code>from itertools import izip_longest def to_dict(keys, values, default=None): return dict(izip_longest(keys, values, fillvalue=default)) </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; to_dict("abcdef", range(3), 10) {'a': 0, 'c': 2, 'b': 1, 'e': 10, 'd': 10, 'f': 10} </code></pre> <p>NOTE: <code>itertools.izip*()</code> functions unlike the <code>zip()</code> function return iterators not lists.</p>
4
2009-02-23T23:59:41Z
[ "python" ]
Need help debugging python html generator
580,397
<p>The program is supposed to take user input, turn it into html and pass it into the clipboard.</p> <p>Start the program with welcome_msg()</p> <p>If you enter 1 in the main menu, it takes you through building an anchor tag. You'll add the link text, the url, then the title. After you enter the title, I get the following errors:</p> <pre><code>File "&lt;pyshell#23&gt;", line 1, in &lt;module&gt; welcome_msg() File "C:\Python26\html_hax.py", line 24, in welcome_msg anchor() File "C:\Python26\html_hax.py", line 71, in anchor copy_to_clipboard(anchor_output) File "C:\Python26\html_hax.py", line 45, in copy_to_clipboard wc.SetClipboardData(win32con.CF_TEXT, msg) error: (0, 'SetClipboardData', 'No error message is available') </code></pre> <p>Here's the Code: <a href="http://pastie.org/398163" rel="nofollow">http://pastie.org/398163</a></p> <p>What is causing the errors above?</p>
1
2009-02-24T03:45:09Z
580,467
<p>In your <code>make_link</code> function you construct a <code>link_output</code>, but you don't actually return it as the functions result. Use <code>return</code> to do this:</p> <pre><code>def make_link(in_link): ... if title == '': link_output = ... else: link_output = ... return link_output </code></pre> <p>This way you get the value passed to your <code>anchor_output</code> variable here:</p> <pre><code>anchor_output = make_link(anchor_text) </code></pre> <p>This was <code>None</code> because the function didn't return any value, and setting the clipboard to <code>None</code> failed. With the function returning a real string it should work as expected.</p>
3
2009-02-24T04:21:41Z
[ "python", "pywin32" ]
Persisting variable value in Python
580,866
<pre><code>for i in range(0,3): j = 0 print 'incrementing ' j += 1 print j </code></pre> <p>prints</p> <pre><code>incrementing 1 incrementing 1 incrementing 1 </code></pre> <p>How can I persist the value of 'j' so that it prints:</p> <pre><code>1 2 3 </code></pre>
0
2009-02-24T08:01:21Z
580,873
<p>You should not reset <code>j</code> to zero in the loop:</p> <pre><code>j = 0 for i in range(0,3): print 'incrementng ' j += 1 print j </code></pre>
16
2009-02-24T08:04:19Z
[ "python", "variables", "loops" ]
Persisting variable value in Python
580,866
<pre><code>for i in range(0,3): j = 0 print 'incrementing ' j += 1 print j </code></pre> <p>prints</p> <pre><code>incrementing 1 incrementing 1 incrementing 1 </code></pre> <p>How can I persist the value of 'j' so that it prints:</p> <pre><code>1 2 3 </code></pre>
0
2009-02-24T08:01:21Z
580,913
<p>A very dirty hack if you want to put this in a function: default arguments! In Python, if a default argument is an array, it becomes "static" and mutable, you can keep it through different calls, like this:</p> <pre><code>def f(j = [0]): j[0] += 1 print('incrementing', j[0]) f() # prints "incrementing 1" f() # prints "incrementing 2" f() # prints "incrementing 3" </code></pre> <p>Have fun!</p> <p><strong>Edit:</strong></p> <p>Amazing, downmoded without any explanation why this hack is bad or off-topic. Default arguments in Python are evaluated at parse-time, am I wrong? I don't think I am, I just expected intelligent answers instead of negative points on my post...</p>
-6
2009-02-24T08:23:04Z
[ "python", "variables", "loops" ]
Python windows File Version attribute
580,924
<p>Last time I asked a similar question but that was about svn related versioning info. Now I am wondering how to query windows "File version" attribute about eg. a dll. I payed attention to wmi and win32file modules as well without success.</p>
16
2009-02-24T08:26:26Z
580,955
<p>You can use the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=49AE8576-9BB9-4126-9761-BA8011FABF38&amp;displaylang=en" rel="nofollow">filever.exe</a> tool to do that. Here'a thread that explains <a href="http://osdir.com/ml/python.windows/2004-02/msg00012.html" rel="nofollow">how to do it from Python</a>. And here's the <a href="http://support.microsoft.com/kb/913111" rel="nofollow">KB article</a> with details about the tool.</p>
2
2009-02-24T08:40:08Z
[ "python", "windows", "file-attributes" ]
Python windows File Version attribute
580,924
<p>Last time I asked a similar question but that was about svn related versioning info. Now I am wondering how to query windows "File version" attribute about eg. a dll. I payed attention to wmi and win32file modules as well without success.</p>
16
2009-02-24T08:26:26Z
594,794
<p>I found this solution at "timgolden" site. Works fine.</p> <pre><code>from win32api import GetFileVersionInfo, LOWORD, HIWORD def get_version_number (filename): info = GetFileVersionInfo (filename, "\\") ms = info['FileVersionMS'] ls = info['FileVersionLS'] return HIWORD (ms), LOWORD (ms), HIWORD (ls), LOWORD (ls) if __name__ == '__main__': import os filename = os.environ["COMSPEC"] print ".".join ([str (i) for i in get_version_number (filename)]) </code></pre>
4
2009-02-27T13:40:42Z
[ "python", "windows", "file-attributes" ]
Python windows File Version attribute
580,924
<p>Last time I asked a similar question but that was about svn related versioning info. Now I am wondering how to query windows "File version" attribute about eg. a dll. I payed attention to wmi and win32file modules as well without success.</p>
16
2009-02-24T08:26:26Z
1,237,635
<p>Better to add a try/except in case the file has no version number attribute.</p> <p>filever.py</p> <pre><code> from win32api import GetFileVersionInfo, LOWORD, HIWORD def get_version_number (filename): try: info = GetFileVersionInfo (filename, "\\") ms = info['FileVersionMS'] ls = info['FileVersionLS'] return HIWORD (ms), LOWORD (ms), HIWORD (ls), LOWORD (ls) except: return 0,0,0,0 if __name__ == '__main__': import os filename = os.environ["COMSPEC"] print ".".join ([str (i) for i in get_version_number (filename)]) </code></pre> <p>yourscript.py:</p> <pre><code> import os,filever myPath="C:\\path\\to\\check" for root, dirs, files in os.walk(myPath): for file in files: file = file.lower() # Convert .EXE to .exe so next line works if (file.count('.exe') or file.count('.dll')): # Check only exe or dll files fullPathToFile=os.path.join(root,file) major,minor,subminor,revision=filever.get_version_number(fullPathToFile) print "Filename: %s \t Version: %s.%s.%s.%s" % (file,major,minor,subminor,revision) </code></pre> <p>Cheers!</p>
16
2009-08-06T08:34:19Z
[ "python", "windows", "file-attributes" ]
Python windows File Version attribute
580,924
<p>Last time I asked a similar question but that was about svn related versioning info. Now I am wondering how to query windows "File version" attribute about eg. a dll. I payed attention to wmi and win32file modules as well without success.</p>
16
2009-02-24T08:26:26Z
2,310,098
<p>You can use the <code>pyWin32</code> module from <a href="http://sourceforge.net/projects/pywin32/">http://sourceforge.net/projects/pywin32/</a>:</p> <pre><code>from win32com.client import Dispatch ver_parser = Dispatch('Scripting.FileSystemObject') info = ver_parser.GetFileVersion(path) if info == 'No Version Information Available': info = None </code></pre>
9
2010-02-22T10:06:42Z
[ "python", "windows", "file-attributes" ]
Python windows File Version attribute
580,924
<p>Last time I asked a similar question but that was about svn related versioning info. Now I am wondering how to query windows "File version" attribute about eg. a dll. I payed attention to wmi and win32file modules as well without success.</p>
16
2009-02-24T08:26:26Z
7,993,095
<p>Here is a function which reads all file attributes as a dictionary:</p> <pre><code>import win32api #============================================================================== def getFileProperties(fname): #============================================================================== """ Read all properties of the given file return them as a dictionary. """ propNames = ('Comments', 'InternalName', 'ProductName', 'CompanyName', 'LegalCopyright', 'ProductVersion', 'FileDescription', 'LegalTrademarks', 'PrivateBuild', 'FileVersion', 'OriginalFilename', 'SpecialBuild') props = {'FixedFileInfo': None, 'StringFileInfo': None, 'FileVersion': None} try: # backslash as parm returns dictionary of numeric info corresponding to VS_FIXEDFILEINFO struc fixedInfo = win32api.GetFileVersionInfo(fname, '\\') props['FixedFileInfo'] = fixedInfo props['FileVersion'] = "%d.%d.%d.%d" % (fixedInfo['FileVersionMS'] / 65536, fixedInfo['FileVersionMS'] % 65536, fixedInfo['FileVersionLS'] / 65536, fixedInfo['FileVersionLS'] % 65536) # \VarFileInfo\Translation returns list of available (language, codepage) # pairs that can be used to retreive string info. We are using only the first pair. lang, codepage = win32api.GetFileVersionInfo(fname, '\\VarFileInfo\\Translation')[0] # any other must be of the form \StringfileInfo\%04X%04X\parm_name, middle # two are language/codepage pair returned from above strInfo = {} for propName in propNames: strInfoPath = u'\\StringFileInfo\\%04X%04X\\%s' % (lang, codepage, propName) ## print str_info strInfo[propName] = win32api.GetFileVersionInfo(fname, strInfoPath) props['StringFileInfo'] = strInfo except: pass return props </code></pre>
13
2011-11-03T10:08:02Z
[ "python", "windows", "file-attributes" ]
Python windows File Version attribute
580,924
<p>Last time I asked a similar question but that was about svn related versioning info. Now I am wondering how to query windows "File version" attribute about eg. a dll. I payed attention to wmi and win32file modules as well without success.</p>
16
2009-02-24T08:26:26Z
16,076,661
<p>Here is a version that also works in non Windows environments, using the <a href="https://code.google.com/p/pefile/">pefile-module</a>:</p> <pre><code>import pefile def LOWORD(dword): return dword &amp; 0x0000ffff def HIWORD(dword): return dword &gt;&gt; 16 def get_product_version(path): pe = pefile.PE(path) #print PE.dump_info() ms = pe.VS_FIXEDFILEINFO.ProductVersionMS ls = pe.VS_FIXEDFILEINFO.ProductVersionLS return (HIWORD (ms), LOWORD (ms), HIWORD (ls), LOWORD (ls)) if __name__ == "__main__": import sys try: print "%d.%d.%d.%d" % get_product_version(sys.argv[1]) except: print "Version info not available. Maybe the file is not a Windows executable" </code></pre>
6
2013-04-18T07:11:09Z
[ "python", "windows", "file-attributes" ]
Python windows File Version attribute
580,924
<p>Last time I asked a similar question but that was about svn related versioning info. Now I am wondering how to query windows "File version" attribute about eg. a dll. I payed attention to wmi and win32file modules as well without success.</p>
16
2009-02-24T08:26:26Z
38,924,793
<p>Here is a version that does not require any additional libraries. I could not use win32api like everyone had suggested:</p> <p>From: <a href="https://mail.python.org/pipermail//python-list/2006-November/402797.html" rel="nofollow">https://mail.python.org/pipermail//python-list/2006-November/402797.html</a></p> <p>Only copied here encase the original goes missing.</p> <pre><code>import array from ctypes import * def get_file_info(filename, info): """ Extract information from a file. """ # Get size needed for buffer (0 if no info) size = windll.version.GetFileVersionInfoSizeA(filename, None) # If no info in file -&gt; empty string if not size: return '' # Create buffer res = create_string_buffer(size) # Load file informations into buffer res windll.version.GetFileVersionInfoA(filename, None, size, res) r = c_uint() l = c_uint() # Look for codepages windll.version.VerQueryValueA(res, '\\VarFileInfo\\Translation', byref(r), byref(l)) # If no codepage -&gt; empty string if not l.value: return '' # Take the first codepage (what else ?) codepages = array.array('H', string_at(r.value, l.value)) codepage = tuple(codepages[:2].tolist()) # Extract information windll.version.VerQueryValueA(res, ('\\StringFileInfo\\%04x%04x\\' + info) % codepage, byref(r), byref(l)) return string_at(r.value, l.value) </code></pre> <p>Used like so: </p> <pre><code> print get_file_info(r'C:\WINDOWS\system32\calc.exe', 'FileVersion') </code></pre>
0
2016-08-12T18:58:24Z
[ "python", "windows", "file-attributes" ]
regex '|' operator vs separate runs for each sub-expression
580,993
<p>I've got a fairly large string (~700k) against which I need to run 10 regexes and count all the matches of any of the regexes. My quick and dirty impl was to do something like re.search('(expr1)|(expr2)|...'), but I was wondering if we'd see any performance gains by matching in a loop instead:</p> <p>In other words, I want to compare the performance of:</p> <pre><code>def CountMatchesInBigstring(bigstring, my_regexes): """Counts how many of the expressions in my_regexes match bigstring.""" count = 0 combined_expr = '|'.join(['(%s)' % r for r in my_regexes]) matches = re.search(combined_expr, bigstring) if matches: count += NumMatches(matches) return count </code></pre> <p>vs</p> <pre><code>def CountMatchesInBigstring(bigstring, my_regexes): """Counts how many of the expressions in my_regexes match bigstring.""" count = 0 for reg in my_regexes: matches = re.search(reg, bigstring) if matches: count += NumMatches(matches) return count </code></pre> <p>I'll stop being lazy and run some tests tomorrow (and post the results), but I wondered whether the answer will jump out to someone who actually understands how regexes work :)</p>
5
2009-02-24T08:55:29Z
581,004
<p>I suspect that the regex will also do what you are trying to do ... only much better :)</p> <p>so the "|" would win</p>
1
2009-02-24T09:00:54Z
[ "python", "regex", "performance" ]
regex '|' operator vs separate runs for each sub-expression
580,993
<p>I've got a fairly large string (~700k) against which I need to run 10 regexes and count all the matches of any of the regexes. My quick and dirty impl was to do something like re.search('(expr1)|(expr2)|...'), but I was wondering if we'd see any performance gains by matching in a loop instead:</p> <p>In other words, I want to compare the performance of:</p> <pre><code>def CountMatchesInBigstring(bigstring, my_regexes): """Counts how many of the expressions in my_regexes match bigstring.""" count = 0 combined_expr = '|'.join(['(%s)' % r for r in my_regexes]) matches = re.search(combined_expr, bigstring) if matches: count += NumMatches(matches) return count </code></pre> <p>vs</p> <pre><code>def CountMatchesInBigstring(bigstring, my_regexes): """Counts how many of the expressions in my_regexes match bigstring.""" count = 0 for reg in my_regexes: matches = re.search(reg, bigstring) if matches: count += NumMatches(matches) return count </code></pre> <p>I'll stop being lazy and run some tests tomorrow (and post the results), but I wondered whether the answer will jump out to someone who actually understands how regexes work :)</p>
5
2009-02-24T08:55:29Z
581,011
<p>The two things will give slightly different results, unless it is guaranteed that a match will match one and only one regex. Otherwise if something matches 2 it will be counted twice.</p> <p>In theory your solution ought to be quicker (if the expression are mutually exclusive) because the regex compiler ought to be able to make a more efficient search state machine, so only one pass is needed. I would expect the difference to be tiny though, unless the expressions are very similar. </p> <p>Also, if it were a huge string (bigger than 700k) there might be gains from doing one pass, and so a factor of n fewer memory swaps would be needed (to disk or cpu cache).</p> <p>My bet is in your tests it isn't really noticeable though. I'm interested in the actual result - please do post the results.</p>
7
2009-02-24T09:03:55Z
[ "python", "regex", "performance" ]
regex '|' operator vs separate runs for each sub-expression
580,993
<p>I've got a fairly large string (~700k) against which I need to run 10 regexes and count all the matches of any of the regexes. My quick and dirty impl was to do something like re.search('(expr1)|(expr2)|...'), but I was wondering if we'd see any performance gains by matching in a loop instead:</p> <p>In other words, I want to compare the performance of:</p> <pre><code>def CountMatchesInBigstring(bigstring, my_regexes): """Counts how many of the expressions in my_regexes match bigstring.""" count = 0 combined_expr = '|'.join(['(%s)' % r for r in my_regexes]) matches = re.search(combined_expr, bigstring) if matches: count += NumMatches(matches) return count </code></pre> <p>vs</p> <pre><code>def CountMatchesInBigstring(bigstring, my_regexes): """Counts how many of the expressions in my_regexes match bigstring.""" count = 0 for reg in my_regexes: matches = re.search(reg, bigstring) if matches: count += NumMatches(matches) return count </code></pre> <p>I'll stop being lazy and run some tests tomorrow (and post the results), but I wondered whether the answer will jump out to someone who actually understands how regexes work :)</p>
5
2009-02-24T08:55:29Z
581,015
<p>I agree with amartynov but I wanted to add that you also might consider compiling the regex first (re.compile()), esp. in the second variant as then you might save some setup time in the loop. Maybe you can measure this as well while you are on it.</p> <p>The reason I think the one shot performs better is that I assume that it's fully done in C space and not so much python code needs to be interpreted.</p> <p>But looking forward to numbers.</p>
0
2009-02-24T09:05:16Z
[ "python", "regex", "performance" ]
regex '|' operator vs separate runs for each sub-expression
580,993
<p>I've got a fairly large string (~700k) against which I need to run 10 regexes and count all the matches of any of the regexes. My quick and dirty impl was to do something like re.search('(expr1)|(expr2)|...'), but I was wondering if we'd see any performance gains by matching in a loop instead:</p> <p>In other words, I want to compare the performance of:</p> <pre><code>def CountMatchesInBigstring(bigstring, my_regexes): """Counts how many of the expressions in my_regexes match bigstring.""" count = 0 combined_expr = '|'.join(['(%s)' % r for r in my_regexes]) matches = re.search(combined_expr, bigstring) if matches: count += NumMatches(matches) return count </code></pre> <p>vs</p> <pre><code>def CountMatchesInBigstring(bigstring, my_regexes): """Counts how many of the expressions in my_regexes match bigstring.""" count = 0 for reg in my_regexes: matches = re.search(reg, bigstring) if matches: count += NumMatches(matches) return count </code></pre> <p>I'll stop being lazy and run some tests tomorrow (and post the results), but I wondered whether the answer will jump out to someone who actually understands how regexes work :)</p>
5
2009-02-24T08:55:29Z
581,018
<p>A single compile and search should yield faster results, on a lower scale of expressions the gain could be negligible but the more you run through the greater gain. Think of it as compiling once and matching vs compiling 10 times and matching.</p>
0
2009-02-24T09:06:22Z
[ "python", "regex", "performance" ]
regex '|' operator vs separate runs for each sub-expression
580,993
<p>I've got a fairly large string (~700k) against which I need to run 10 regexes and count all the matches of any of the regexes. My quick and dirty impl was to do something like re.search('(expr1)|(expr2)|...'), but I was wondering if we'd see any performance gains by matching in a loop instead:</p> <p>In other words, I want to compare the performance of:</p> <pre><code>def CountMatchesInBigstring(bigstring, my_regexes): """Counts how many of the expressions in my_regexes match bigstring.""" count = 0 combined_expr = '|'.join(['(%s)' % r for r in my_regexes]) matches = re.search(combined_expr, bigstring) if matches: count += NumMatches(matches) return count </code></pre> <p>vs</p> <pre><code>def CountMatchesInBigstring(bigstring, my_regexes): """Counts how many of the expressions in my_regexes match bigstring.""" count = 0 for reg in my_regexes: matches = re.search(reg, bigstring) if matches: count += NumMatches(matches) return count </code></pre> <p>I'll stop being lazy and run some tests tomorrow (and post the results), but I wondered whether the answer will jump out to someone who actually understands how regexes work :)</p>
5
2009-02-24T08:55:29Z
581,029
<p>I believe your first implementation will be faster:</p> <ul> <li>One of the key principles for Python performance is "move logic to the C level" -- meaning built-in functions (written in C) are faster than pure-Python implementations. So, when the loop is performed by the built-in Regex module, it should be faster</li> <li>One regex can search for multiple pattens in one pass, meaning it only has to run through your file contents once, whereas multiple regex will have to read the whole file multiple times.</li> </ul>
1
2009-02-24T09:10:06Z
[ "python", "regex", "performance" ]
regex '|' operator vs separate runs for each sub-expression
580,993
<p>I've got a fairly large string (~700k) against which I need to run 10 regexes and count all the matches of any of the regexes. My quick and dirty impl was to do something like re.search('(expr1)|(expr2)|...'), but I was wondering if we'd see any performance gains by matching in a loop instead:</p> <p>In other words, I want to compare the performance of:</p> <pre><code>def CountMatchesInBigstring(bigstring, my_regexes): """Counts how many of the expressions in my_regexes match bigstring.""" count = 0 combined_expr = '|'.join(['(%s)' % r for r in my_regexes]) matches = re.search(combined_expr, bigstring) if matches: count += NumMatches(matches) return count </code></pre> <p>vs</p> <pre><code>def CountMatchesInBigstring(bigstring, my_regexes): """Counts how many of the expressions in my_regexes match bigstring.""" count = 0 for reg in my_regexes: matches = re.search(reg, bigstring) if matches: count += NumMatches(matches) return count </code></pre> <p>I'll stop being lazy and run some tests tomorrow (and post the results), but I wondered whether the answer will jump out to someone who actually understands how regexes work :)</p>
5
2009-02-24T08:55:29Z
582,227
<p>To understand how re module works - compile _sre.c in debug mode (put #define VERBOSE at 103 line in _sre.c and recompile python). After this you ill see something like this:</p> <pre> <code> >>> import re >>> p = re.compile('(a)|(b)|(c)') >>> p.search('a'); print '\n\n'; p.search('b') |0xb7f9ab10|(nil)|SEARCH prefix = (nil) 0 0 charset = (nil) |0xb7f9ab1a|0xb7fb75f4|SEARCH |0xb7f9ab1a|0xb7fb75f4|ENTER allocating sre_match_context in 0 (32) allocate/grow stack 1064 |0xb7f9ab1c|0xb7fb75f4|BRANCH allocating sre_match_context in 32 (32) |0xb7f9ab20|0xb7fb75f4|MARK 0 |0xb7f9ab24|0xb7fb75f4|LITERAL 97 |0xb7f9ab28|0xb7fb75f5|MARK 1 |0xb7f9ab2c|0xb7fb75f5|JUMP 20 |0xb7f9ab56|0xb7fb75f5|SUCCESS discard data from 32 (32) looking up sre_match_context at 0 |0xb7f9ab1c|0xb7fb75f4|JUMP_BRANCH discard data from 0 (32) |0xb7f9ab10|0xb7fb75f5|END |0xb7f9ab10|(nil)|SEARCH prefix = (nil) 0 0 charset = (nil) |0xb7f9ab1a|0xb7fb7614|SEARCH |0xb7f9ab1a|0xb7fb7614|ENTER allocating sre_match_context in 0 (32) allocate/grow stack 1064 |0xb7f9ab1c|0xb7fb7614|BRANCH allocating sre_match_context in 32 (32) |0xb7f9ab20|0xb7fb7614|MARK 0 |0xb7f9ab24|0xb7fb7614|LITERAL 97 discard data from 32 (32) looking up sre_match_context at 0 |0xb7f9ab1c|0xb7fb7614|JUMP_BRANCH allocating sre_match_context in 32 (32) |0xb7f9ab32|0xb7fb7614|MARK 2 |0xb7f9ab36|0xb7fb7614|LITERAL 98 |0xb7f9ab3a|0xb7fb7615|MARK 3 |0xb7f9ab3e|0xb7fb7615|JUMP 11 |0xb7f9ab56|0xb7fb7615|SUCCESS discard data from 32 (32) looking up sre_match_context at 0 |0xb7f9ab2e|0xb7fb7614|JUMP_BRANCH discard data from 0 (32) |0xb7f9ab10|0xb7fb7615|END >>> </code> </pre>
5
2009-02-24T15:40:35Z
[ "python", "regex", "performance" ]
regex '|' operator vs separate runs for each sub-expression
580,993
<p>I've got a fairly large string (~700k) against which I need to run 10 regexes and count all the matches of any of the regexes. My quick and dirty impl was to do something like re.search('(expr1)|(expr2)|...'), but I was wondering if we'd see any performance gains by matching in a loop instead:</p> <p>In other words, I want to compare the performance of:</p> <pre><code>def CountMatchesInBigstring(bigstring, my_regexes): """Counts how many of the expressions in my_regexes match bigstring.""" count = 0 combined_expr = '|'.join(['(%s)' % r for r in my_regexes]) matches = re.search(combined_expr, bigstring) if matches: count += NumMatches(matches) return count </code></pre> <p>vs</p> <pre><code>def CountMatchesInBigstring(bigstring, my_regexes): """Counts how many of the expressions in my_regexes match bigstring.""" count = 0 for reg in my_regexes: matches = re.search(reg, bigstring) if matches: count += NumMatches(matches) return count </code></pre> <p>I'll stop being lazy and run some tests tomorrow (and post the results), but I wondered whether the answer will jump out to someone who actually understands how regexes work :)</p>
5
2009-02-24T08:55:29Z
583,320
<p>The fewer passes the better: It'll just use more memory, which is typically not an issue.</p> <p>If anything can be left to the interpreter to handle, it will always find a faster solution (both in time to implement and time to execute) than the typical human counterpart.</p>
0
2009-02-24T19:59:17Z
[ "python", "regex", "performance" ]
Python web programming
581,038
<p>Good morning.</p> <p>As the title indicates, I've got some questions about using python for web development.</p> <ul> <li>What is the best setup for a development environment, more specifically, what webserver to use, how to bind python with it. Preferably, I'd like it to be implementable in both, *nix and win environment.</li> </ul> <p>My major concern when I last tried apache + mod_python + CherryPy was having to reload webserver to see the changes. Is it considered normal? For some reason cherrypy's autoreload didn't work at all.</p> <ul> <li><p>What is the best setup to deploy a working Python app to production and why? I'm now using lighttpd for my PHP web apps, but how would it do for python compared to nginx for example?</p></li> <li><p>Is it worth diving straight with a framework or to roll something simple of my own? I see that Django has got quite a lot of fans, but I'm thinking it would be overkill for my needs, so I've started looking into CherryPy.</p></li> <li><p>How exactly are Python apps served if I have to reload httpd to see the changes? Something like a permanent process spawning child processes, with all the major file includes happening on server start and then just lazy loading needed resources?</p></li> <li><p>Python supports multithreading, do I need to look into using that for a benefit when developing web apps? What would be that benefit and in what situations?</p></li> </ul> <p>Big thanks!</p>
12
2009-02-24T09:15:24Z
581,077
<p>So here are my thoughts about it:</p> <p>I am using <a href="http://pythonpaste.org/" rel="nofollow">Python Paste</a> for developing my app and eventually also running it (or any other python web server). I am usually not using mod_python or mod_wsgi as it makes development setup more complex.</p> <p>I am using <a href="http://pypi.python.org/pypi/zc.buildout" rel="nofollow">zc.buildout</a> for managing my development environment and all dependencies together with <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a>. This gives me an isolated sandbox which does not interfere with any Python modules installed system wide. </p> <p>For deployment I am also using buildout/virtualenv, eventually with a different buildout.cfg. I am also using <a href="http://pythonpaste.org/deploy/" rel="nofollow">Paste Deploy</a> and it's configuration mechanism where I have different config files for development and deployment.</p> <p>As I am usually running paste/cherrypy etc. standalone I am using Apache, NGINX or maybe just a Varnish alone in front of it. It depends on what configuration options you need. E.g. if no virtual hosting, rewrite rules etc. are needed, then I don't need a full featured web server in front. When using a web server I usually use ProxyPass or some more complex rewriting using mod_rewrite.</p> <p>The Python web framework I use at the moment is <a href="http://static.repoze.org/bfgdocs/" rel="nofollow">repoze.bfg</a> right now btw.</p> <p>As for your questions about reloading I know about these problems when running it with e.g. mod_python but when using a standalone "paster serve ... -reload" etc. it so far works really well. repoze.bfg additionally has some setting for automatically reloading templates when they change. If the framework you use has that should be documented.</p> <p>As for multithreading that's usually used then inside the python web server. As CherryPy supports this I guess you don't have to worry about that, it should be used automatically. You should just eventually make some benchmarks to find out under what number of threads your application performs the best.</p> <p>Hope that helps.</p>
6
2009-02-24T09:26:54Z
[ "python", "cherrypy" ]
Python web programming
581,038
<p>Good morning.</p> <p>As the title indicates, I've got some questions about using python for web development.</p> <ul> <li>What is the best setup for a development environment, more specifically, what webserver to use, how to bind python with it. Preferably, I'd like it to be implementable in both, *nix and win environment.</li> </ul> <p>My major concern when I last tried apache + mod_python + CherryPy was having to reload webserver to see the changes. Is it considered normal? For some reason cherrypy's autoreload didn't work at all.</p> <ul> <li><p>What is the best setup to deploy a working Python app to production and why? I'm now using lighttpd for my PHP web apps, but how would it do for python compared to nginx for example?</p></li> <li><p>Is it worth diving straight with a framework or to roll something simple of my own? I see that Django has got quite a lot of fans, but I'm thinking it would be overkill for my needs, so I've started looking into CherryPy.</p></li> <li><p>How exactly are Python apps served if I have to reload httpd to see the changes? Something like a permanent process spawning child processes, with all the major file includes happening on server start and then just lazy loading needed resources?</p></li> <li><p>Python supports multithreading, do I need to look into using that for a benefit when developing web apps? What would be that benefit and in what situations?</p></li> </ul> <p>Big thanks!</p>
12
2009-02-24T09:15:24Z
581,155
<p>+1 to MrTopf's answer, but I'll add some additional opinions.</p> <p><strong>Webserver</strong></p> <p>Apache is the webserver that will give you the most configurability. Avoid mod_python because it is basically unsupported. On the other hand, <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a> is very well supported and gives you better stability (in other words, easier to configure for cpu/memory usage to be stable as opposed to spikey and unpredictable).</p> <p>Another huge benefit, you can configure mod_wsgi to reload your application if the wsgi application script is touched, no need to restart Apache. For development/testing servers you can even configure mod_wsgi to reload when any file in your application is changed. This is so helpful I even run Apache+mod_wsgi on my laptop during development.</p> <p>Nginx and lighttpd are commonly used for webservers, either by serving Python apps directly through a fastCGI interface (don't bother with any WSGI interfaces on these servers yet) or by using them as a front end in front of Apache. Calls into the app get passed through (by proxy) to Apache+mod_wsgi and then nginx/lighttpd serve the static content directly.</p> <p>Nginx has the added advantage of being able to serve content directly from memcached if you want to get that sophisticated. I've heard disparaging comments about lighttpd and it does seem to have some development problems, but there are certainly some big companies using it successfully.</p> <p><strong>Python stack</strong></p> <p>At the lowest level you can program to WSGI directly for the best performance. There are lots of helpful WSGI modules out there to help you in areas you don't want to develop yourself. At this level you'll probably want to pick third-party WSGI components to do things like URL resolving and HTTP request/response handling. A great request/response component is <a href="http://pythonpaste.org/webob/" rel="nofollow">WebOb</a>.</p> <p>If you look at <a href="http://pylonshq.com/" rel="nofollow">Pylons</a> you can see their idea of "best-of-breed" WSGI components and a framework that makes it easier than Django to choose your own components like templating engine.</p> <p>Django might be overkill but I don't think that's a really good argument against. Django makes the easy stuff easier. When you start to get into very complicated applications is where you really need to look at moving to lower level frameworks.</p>
6
2009-02-24T09:54:17Z
[ "python", "cherrypy" ]
Python web programming
581,038
<p>Good morning.</p> <p>As the title indicates, I've got some questions about using python for web development.</p> <ul> <li>What is the best setup for a development environment, more specifically, what webserver to use, how to bind python with it. Preferably, I'd like it to be implementable in both, *nix and win environment.</li> </ul> <p>My major concern when I last tried apache + mod_python + CherryPy was having to reload webserver to see the changes. Is it considered normal? For some reason cherrypy's autoreload didn't work at all.</p> <ul> <li><p>What is the best setup to deploy a working Python app to production and why? I'm now using lighttpd for my PHP web apps, but how would it do for python compared to nginx for example?</p></li> <li><p>Is it worth diving straight with a framework or to roll something simple of my own? I see that Django has got quite a lot of fans, but I'm thinking it would be overkill for my needs, so I've started looking into CherryPy.</p></li> <li><p>How exactly are Python apps served if I have to reload httpd to see the changes? Something like a permanent process spawning child processes, with all the major file includes happening on server start and then just lazy loading needed resources?</p></li> <li><p>Python supports multithreading, do I need to look into using that for a benefit when developing web apps? What would be that benefit and in what situations?</p></li> </ul> <p>Big thanks!</p>
12
2009-02-24T09:15:24Z
581,356
<p><strong>What is the best setup for a development environment?</strong></p> <p>Doesn't much matter. We use Django, which runs in Windows and Unix nicely. For production, we use Apache in Red Hat.</p> <p><strong>Is having to reload webserver to see the changes considered normal?</strong></p> <p>Yes. Not clear why you'd want anything different. Web application software shouldn't be dynamic. Content yes. Software no.</p> <p>In Django, we <em>develop</em> without using a web server of any kind on our desktop. The Django "runserver" command reloads the application under most circumstances. For development, this works great. The times when it won't reload are when we've damaged things so badly that the app doesn't properly.</p> <p><strong>What is the best setup to deploy a working Python app to production and why?</strong></p> <p>"Best" is undefined in this context. Therefore, please provide some qualification for "nest" (e.g., "fastest", "cheapest", "bluest")</p> <p><strong>Is it worth diving straight with a framework or to roll something simple of my own?</strong></p> <p>Don't waste time rolling your own. We use Django because of the built-in admin page that we don't have to write or maintain. Saves mountains of work.</p> <p><strong>How exactly are Python apps served if I have to reload httpd to see the changes?</strong></p> <p>Two methods:</p> <ul> <li><p>Daemon - mod_wsgi or mod_fastcgi have a Python daemon process to which they connect. Change your software. Restart the daemon.</p></li> <li><p>Embedded - mod_wsgi or mod_python have an embedded mode in which the Python interpreter is inside the mod, inside Apache. You have to restart httpd to restart that embedded interpreter.</p></li> </ul> <p><strong>Do I need to look into using multi-threaded?</strong></p> <p>Yes and no. Yes you do need to be aware of this. No, you don't need to do very much. Apache and mod_wsgi and Django should handle this for you.</p>
8
2009-02-24T11:05:43Z
[ "python", "cherrypy" ]
Python web programming
581,038
<p>Good morning.</p> <p>As the title indicates, I've got some questions about using python for web development.</p> <ul> <li>What is the best setup for a development environment, more specifically, what webserver to use, how to bind python with it. Preferably, I'd like it to be implementable in both, *nix and win environment.</li> </ul> <p>My major concern when I last tried apache + mod_python + CherryPy was having to reload webserver to see the changes. Is it considered normal? For some reason cherrypy's autoreload didn't work at all.</p> <ul> <li><p>What is the best setup to deploy a working Python app to production and why? I'm now using lighttpd for my PHP web apps, but how would it do for python compared to nginx for example?</p></li> <li><p>Is it worth diving straight with a framework or to roll something simple of my own? I see that Django has got quite a lot of fans, but I'm thinking it would be overkill for my needs, so I've started looking into CherryPy.</p></li> <li><p>How exactly are Python apps served if I have to reload httpd to see the changes? Something like a permanent process spawning child processes, with all the major file includes happening on server start and then just lazy loading needed resources?</p></li> <li><p>Python supports multithreading, do I need to look into using that for a benefit when developing web apps? What would be that benefit and in what situations?</p></li> </ul> <p>Big thanks!</p>
12
2009-02-24T09:15:24Z
582,467
<p>When you use <code>mod_python</code> on a threaded Apache server (the default on Windows), CherryPy runs in the same process as Apache. In that case, you almost certainly <strong>don't</strong> want CP to restart the process.</p> <p>Solution: use <code>mod_rewrite</code> or <code>mod_proxy</code> so that CherryPy runs in its own process. Then you can autoreload to your heart's content. :)</p>
1
2009-02-24T16:33:18Z
[ "python", "cherrypy" ]
Python web programming
581,038
<p>Good morning.</p> <p>As the title indicates, I've got some questions about using python for web development.</p> <ul> <li>What is the best setup for a development environment, more specifically, what webserver to use, how to bind python with it. Preferably, I'd like it to be implementable in both, *nix and win environment.</li> </ul> <p>My major concern when I last tried apache + mod_python + CherryPy was having to reload webserver to see the changes. Is it considered normal? For some reason cherrypy's autoreload didn't work at all.</p> <ul> <li><p>What is the best setup to deploy a working Python app to production and why? I'm now using lighttpd for my PHP web apps, but how would it do for python compared to nginx for example?</p></li> <li><p>Is it worth diving straight with a framework or to roll something simple of my own? I see that Django has got quite a lot of fans, but I'm thinking it would be overkill for my needs, so I've started looking into CherryPy.</p></li> <li><p>How exactly are Python apps served if I have to reload httpd to see the changes? Something like a permanent process spawning child processes, with all the major file includes happening on server start and then just lazy loading needed resources?</p></li> <li><p>Python supports multithreading, do I need to look into using that for a benefit when developing web apps? What would be that benefit and in what situations?</p></li> </ul> <p>Big thanks!</p>
12
2009-02-24T09:15:24Z
582,691
<p>Look at Google App Engine. From their website: </p> <blockquote> <p>Google App Engine lets you run your web applications on Google's infrastructure. App Engine applications are easy to build, easy to maintain, and easy to scale as your traffic and data storage needs grow. With App Engine, there are no servers to maintain: You just upload your application, and it's ready to serve your users.</p> <p>You can serve your app using a free domain name on the appspot.com domain, or use Google Apps to serve it from your own domain. You can share your application with the world, or limit access to members of your organization.</p> <p>App Engine costs nothing to get started. Sign up for a free account, and you can develop and publish your application for the world to see, at no charge and with no obligation. A free account can use up to 500MB of persistent storage and enough CPU and bandwidth for about 5 million page views a month.</p> </blockquote> <p>Best part of all: It includes Python support, including Django. Go to <a href="http://code.google.com/appengine/docs/whatisgoogleappengine.html" rel="nofollow">http://code.google.com/appengine/docs/whatisgoogleappengine.html</a></p>
2
2009-02-24T17:30:04Z
[ "python", "cherrypy" ]
Double buffering with wxpython
581,085
<p>I'm working on an multiplatform application with wxpython and I had flickering problems on windows, while drawing on a Panel. I used to draw on a buffer (wx.Bitmap) during mouse motions events and my OnPaint method was composed of just on line:</p> <pre><code>dc = wx.BufferedPaintDC(self, self.buffer) </code></pre> <p>Pretty standard but still I had flickering problems on Windows, while everything worked fine on Linux.</p> <p>I <strong>solved my problem</strong> calling <code>SetDoubleBuffered(True)</code> in the <code>__init__</code> method.</p> <p>The strange thing is that now everything works even if I don't use BufferedPaintDC anymore. I changed my application so that all the drawing part is done in the OnPaint method. I don't use a buffer and drawing is done directly on a wx.PaintDC with no flickering problems at all.</p> <p>So my question is: is BufferedPaintDC totally useless? Or deprecated somehow? I'm owner of the book "WxPython in Action" (2006) and it doesn't even mention SetDoubleBuffered</p>
10
2009-02-24T09:29:15Z
582,568
<p>There is a high probability that the SetDoubleBuffered actually makes your panel use a buffered dc automatically, the documentation doesn't mention that those classes are deprecated (and I rather think they would if that were the case).</p> <p>About wxPython in Action... 2006 was a long time ago... it is possible that the SetDoubleBuffered method didn't exist back then or that the author wanted to show how things work at the lower level.</p>
5
2009-02-24T17:00:58Z
[ "python", "user-interface", "wxpython", "doublebuffered" ]
Can someone explain why scipy.integrate.quad gives different results for equally long ranges while integrating sin(X)?
581,186
<p>I am trying to numerically integrate an arbitrary (known when I code) function in my program using numerical integration methods. I am using Python 2.5.2 along with SciPy's numerical integration package. In order to get a feel for it, i decided to try integrating sin(x) and observed this behavior-</p> <pre><code>&gt;&gt;&gt; from math import pi &gt;&gt;&gt; from scipy.integrate import quad &gt;&gt;&gt; from math import sin &gt;&gt;&gt; def integrand(x): ... return sin(x) ... &gt;&gt;&gt; quad(integrand, -pi, pi) (0.0, 4.3998892617846002e-14) &gt;&gt;&gt; quad(integrand, 0, 2*pi) (2.2579473462709165e-16, 4.3998892617846002e-14) </code></pre> <p>I find this behavior odd because -<br /> 1. In ordinary integration, integrating over the full cycle gives zero.<br /> 2. In numerical integration, this (1) isn't necessarily the case, because you may just be approximating the total area under the curve.</p> <p>In any case, either assuming 1 is True or assuming 2 is True, I find the behavior to be inconsistent. Either both integrations (-pi to pi and 0 to 2*pi) should return 0.0 (first value in the tuple is the result and the second is the error) or return 2.257...</p> <p>Can someone please explain why this is happening? Is this really an inconsistency? Can someone also tell me if I am missing something really basic about numerical methods?</p> <p>In any case, in my final application, I plan to use the above method to find the arc length of a function. If someone has experience in this area, please advise me on the best policy for doing this in Python.</p> <p><strong>Edit</strong><br /> <strong>Note</strong><br /> I already have the first differential values at all points in the range stored in an array.<br /> Current error is tolerable.<br /> <strong>End note</strong></p> <p>I have read Wikipaedia on this. As Dimitry has pointed out, I will be integrating sqrt(1+diff(f(x), x)^2) to get the Arc Length. What I wanted to ask was - is there a better approximation/ Best practice(?) / faster way to do this. If more context is needed, I'll post it separately/ post context here, as you wish.</p>
3
2009-02-24T10:10:29Z
581,225
<p>This output seems correct to me since you have absolute error estimate here. The integral value of sin(x) is indeed should have value of zero for full period (any interval of 2*pi length) in both ordinary and numeric integration and your results is close to that value.<br /> To evaluate arc length you should calculate integral for sqrt(1+diff(f(x), x)^2) function, where diff(f(x), x) is derivative of f(x). See also <a href="http://en.wikipedia.org/wiki/Arclength" rel="nofollow">Arc length</a></p>
4
2009-02-24T10:22:12Z
[ "python", "integration", "scipy", "numerical-methods" ]
Can someone explain why scipy.integrate.quad gives different results for equally long ranges while integrating sin(X)?
581,186
<p>I am trying to numerically integrate an arbitrary (known when I code) function in my program using numerical integration methods. I am using Python 2.5.2 along with SciPy's numerical integration package. In order to get a feel for it, i decided to try integrating sin(x) and observed this behavior-</p> <pre><code>&gt;&gt;&gt; from math import pi &gt;&gt;&gt; from scipy.integrate import quad &gt;&gt;&gt; from math import sin &gt;&gt;&gt; def integrand(x): ... return sin(x) ... &gt;&gt;&gt; quad(integrand, -pi, pi) (0.0, 4.3998892617846002e-14) &gt;&gt;&gt; quad(integrand, 0, 2*pi) (2.2579473462709165e-16, 4.3998892617846002e-14) </code></pre> <p>I find this behavior odd because -<br /> 1. In ordinary integration, integrating over the full cycle gives zero.<br /> 2. In numerical integration, this (1) isn't necessarily the case, because you may just be approximating the total area under the curve.</p> <p>In any case, either assuming 1 is True or assuming 2 is True, I find the behavior to be inconsistent. Either both integrations (-pi to pi and 0 to 2*pi) should return 0.0 (first value in the tuple is the result and the second is the error) or return 2.257...</p> <p>Can someone please explain why this is happening? Is this really an inconsistency? Can someone also tell me if I am missing something really basic about numerical methods?</p> <p>In any case, in my final application, I plan to use the above method to find the arc length of a function. If someone has experience in this area, please advise me on the best policy for doing this in Python.</p> <p><strong>Edit</strong><br /> <strong>Note</strong><br /> I already have the first differential values at all points in the range stored in an array.<br /> Current error is tolerable.<br /> <strong>End note</strong></p> <p>I have read Wikipaedia on this. As Dimitry has pointed out, I will be integrating sqrt(1+diff(f(x), x)^2) to get the Arc Length. What I wanted to ask was - is there a better approximation/ Best practice(?) / faster way to do this. If more context is needed, I'll post it separately/ post context here, as you wish.</p>
3
2009-02-24T10:10:29Z
581,250
<p>The <code>quad</code> function is a function from an old Fortran library. It works by judging by the flatness and slope of the function it is integrating how to treat the step size it uses for numerical integration in order to maximize efficiency. What this means is that you may get slightly different answers from one region to the next even if they're analytically the same.</p> <p>Without a doubt both integrations should return zero. Returning something that is 1/(10 trillion) is pretty close to zero! The slight differences are due to the way <code>quad</code> is rolling over <code>sin</code> and changing its step sizes. For your planned task, <code>quad</code> will be all you need.</p> <p>EDIT: For what you're doing I think <code>quad</code> is fine. It is fast and pretty accurate. My final statement is use it with confidence unless you find something that really has gone quite awry. If it doesn't return a nonsensical answer then it is probably working just fine. No worries.</p>
7
2009-02-24T10:32:18Z
[ "python", "integration", "scipy", "numerical-methods" ]
Can someone explain why scipy.integrate.quad gives different results for equally long ranges while integrating sin(X)?
581,186
<p>I am trying to numerically integrate an arbitrary (known when I code) function in my program using numerical integration methods. I am using Python 2.5.2 along with SciPy's numerical integration package. In order to get a feel for it, i decided to try integrating sin(x) and observed this behavior-</p> <pre><code>&gt;&gt;&gt; from math import pi &gt;&gt;&gt; from scipy.integrate import quad &gt;&gt;&gt; from math import sin &gt;&gt;&gt; def integrand(x): ... return sin(x) ... &gt;&gt;&gt; quad(integrand, -pi, pi) (0.0, 4.3998892617846002e-14) &gt;&gt;&gt; quad(integrand, 0, 2*pi) (2.2579473462709165e-16, 4.3998892617846002e-14) </code></pre> <p>I find this behavior odd because -<br /> 1. In ordinary integration, integrating over the full cycle gives zero.<br /> 2. In numerical integration, this (1) isn't necessarily the case, because you may just be approximating the total area under the curve.</p> <p>In any case, either assuming 1 is True or assuming 2 is True, I find the behavior to be inconsistent. Either both integrations (-pi to pi and 0 to 2*pi) should return 0.0 (first value in the tuple is the result and the second is the error) or return 2.257...</p> <p>Can someone please explain why this is happening? Is this really an inconsistency? Can someone also tell me if I am missing something really basic about numerical methods?</p> <p>In any case, in my final application, I plan to use the above method to find the arc length of a function. If someone has experience in this area, please advise me on the best policy for doing this in Python.</p> <p><strong>Edit</strong><br /> <strong>Note</strong><br /> I already have the first differential values at all points in the range stored in an array.<br /> Current error is tolerable.<br /> <strong>End note</strong></p> <p>I have read Wikipaedia on this. As Dimitry has pointed out, I will be integrating sqrt(1+diff(f(x), x)^2) to get the Arc Length. What I wanted to ask was - is there a better approximation/ Best practice(?) / faster way to do this. If more context is needed, I'll post it separately/ post context here, as you wish.</p>
3
2009-02-24T10:10:29Z
581,254
<p>I think it is probably machine precision since both answers are effectively zero.</p> <p>If you want an answer from the horse's mouth I would post this question on the <a href="http://www.nabble.com/Scipy-User-f33045.html">scipy discussion board</a></p>
6
2009-02-24T10:32:55Z
[ "python", "integration", "scipy", "numerical-methods" ]
Can someone explain why scipy.integrate.quad gives different results for equally long ranges while integrating sin(X)?
581,186
<p>I am trying to numerically integrate an arbitrary (known when I code) function in my program using numerical integration methods. I am using Python 2.5.2 along with SciPy's numerical integration package. In order to get a feel for it, i decided to try integrating sin(x) and observed this behavior-</p> <pre><code>&gt;&gt;&gt; from math import pi &gt;&gt;&gt; from scipy.integrate import quad &gt;&gt;&gt; from math import sin &gt;&gt;&gt; def integrand(x): ... return sin(x) ... &gt;&gt;&gt; quad(integrand, -pi, pi) (0.0, 4.3998892617846002e-14) &gt;&gt;&gt; quad(integrand, 0, 2*pi) (2.2579473462709165e-16, 4.3998892617846002e-14) </code></pre> <p>I find this behavior odd because -<br /> 1. In ordinary integration, integrating over the full cycle gives zero.<br /> 2. In numerical integration, this (1) isn't necessarily the case, because you may just be approximating the total area under the curve.</p> <p>In any case, either assuming 1 is True or assuming 2 is True, I find the behavior to be inconsistent. Either both integrations (-pi to pi and 0 to 2*pi) should return 0.0 (first value in the tuple is the result and the second is the error) or return 2.257...</p> <p>Can someone please explain why this is happening? Is this really an inconsistency? Can someone also tell me if I am missing something really basic about numerical methods?</p> <p>In any case, in my final application, I plan to use the above method to find the arc length of a function. If someone has experience in this area, please advise me on the best policy for doing this in Python.</p> <p><strong>Edit</strong><br /> <strong>Note</strong><br /> I already have the first differential values at all points in the range stored in an array.<br /> Current error is tolerable.<br /> <strong>End note</strong></p> <p>I have read Wikipaedia on this. As Dimitry has pointed out, I will be integrating sqrt(1+diff(f(x), x)^2) to get the Arc Length. What I wanted to ask was - is there a better approximation/ Best practice(?) / faster way to do this. If more context is needed, I'll post it separately/ post context here, as you wish.</p>
3
2009-02-24T10:10:29Z
581,313
<p>I would say that a number O(10^-14) is effectively zero. What's your tolerance?</p> <p>It might be that the algorithm underlying quad isn't the best. You might try another method for integration and see if that improves things. A 5th order Runge-Kutta can be a very nice general purpose technique.</p> <p>It could be just the nature of floating point numbers: <a href="http://www.physics.ohio-state.edu/~dws/grouplinks/floating%5Fpoint%5Fmath.pdf">"What Every Computer Scientist Should Know About Floating Point Arithmetic".</a></p>
6
2009-02-24T10:52:04Z
[ "python", "integration", "scipy", "numerical-methods" ]
Can someone explain why scipy.integrate.quad gives different results for equally long ranges while integrating sin(X)?
581,186
<p>I am trying to numerically integrate an arbitrary (known when I code) function in my program using numerical integration methods. I am using Python 2.5.2 along with SciPy's numerical integration package. In order to get a feel for it, i decided to try integrating sin(x) and observed this behavior-</p> <pre><code>&gt;&gt;&gt; from math import pi &gt;&gt;&gt; from scipy.integrate import quad &gt;&gt;&gt; from math import sin &gt;&gt;&gt; def integrand(x): ... return sin(x) ... &gt;&gt;&gt; quad(integrand, -pi, pi) (0.0, 4.3998892617846002e-14) &gt;&gt;&gt; quad(integrand, 0, 2*pi) (2.2579473462709165e-16, 4.3998892617846002e-14) </code></pre> <p>I find this behavior odd because -<br /> 1. In ordinary integration, integrating over the full cycle gives zero.<br /> 2. In numerical integration, this (1) isn't necessarily the case, because you may just be approximating the total area under the curve.</p> <p>In any case, either assuming 1 is True or assuming 2 is True, I find the behavior to be inconsistent. Either both integrations (-pi to pi and 0 to 2*pi) should return 0.0 (first value in the tuple is the result and the second is the error) or return 2.257...</p> <p>Can someone please explain why this is happening? Is this really an inconsistency? Can someone also tell me if I am missing something really basic about numerical methods?</p> <p>In any case, in my final application, I plan to use the above method to find the arc length of a function. If someone has experience in this area, please advise me on the best policy for doing this in Python.</p> <p><strong>Edit</strong><br /> <strong>Note</strong><br /> I already have the first differential values at all points in the range stored in an array.<br /> Current error is tolerable.<br /> <strong>End note</strong></p> <p>I have read Wikipaedia on this. As Dimitry has pointed out, I will be integrating sqrt(1+diff(f(x), x)^2) to get the Arc Length. What I wanted to ask was - is there a better approximation/ Best practice(?) / faster way to do this. If more context is needed, I'll post it separately/ post context here, as you wish.</p>
3
2009-02-24T10:10:29Z
584,185
<pre><code>0.0 == 2.3e-16 (absolute error tolerance 4.4e-14) </code></pre> <p>Both answers are the same and <em>correct</em> i.e., zero within the given tolerance.</p>
3
2009-02-24T23:53:11Z
[ "python", "integration", "scipy", "numerical-methods" ]
Can someone explain why scipy.integrate.quad gives different results for equally long ranges while integrating sin(X)?
581,186
<p>I am trying to numerically integrate an arbitrary (known when I code) function in my program using numerical integration methods. I am using Python 2.5.2 along with SciPy's numerical integration package. In order to get a feel for it, i decided to try integrating sin(x) and observed this behavior-</p> <pre><code>&gt;&gt;&gt; from math import pi &gt;&gt;&gt; from scipy.integrate import quad &gt;&gt;&gt; from math import sin &gt;&gt;&gt; def integrand(x): ... return sin(x) ... &gt;&gt;&gt; quad(integrand, -pi, pi) (0.0, 4.3998892617846002e-14) &gt;&gt;&gt; quad(integrand, 0, 2*pi) (2.2579473462709165e-16, 4.3998892617846002e-14) </code></pre> <p>I find this behavior odd because -<br /> 1. In ordinary integration, integrating over the full cycle gives zero.<br /> 2. In numerical integration, this (1) isn't necessarily the case, because you may just be approximating the total area under the curve.</p> <p>In any case, either assuming 1 is True or assuming 2 is True, I find the behavior to be inconsistent. Either both integrations (-pi to pi and 0 to 2*pi) should return 0.0 (first value in the tuple is the result and the second is the error) or return 2.257...</p> <p>Can someone please explain why this is happening? Is this really an inconsistency? Can someone also tell me if I am missing something really basic about numerical methods?</p> <p>In any case, in my final application, I plan to use the above method to find the arc length of a function. If someone has experience in this area, please advise me on the best policy for doing this in Python.</p> <p><strong>Edit</strong><br /> <strong>Note</strong><br /> I already have the first differential values at all points in the range stored in an array.<br /> Current error is tolerable.<br /> <strong>End note</strong></p> <p>I have read Wikipaedia on this. As Dimitry has pointed out, I will be integrating sqrt(1+diff(f(x), x)^2) to get the Arc Length. What I wanted to ask was - is there a better approximation/ Best practice(?) / faster way to do this. If more context is needed, I'll post it separately/ post context here, as you wish.</p>
3
2009-02-24T10:10:29Z
1,848,828
<p>The difference comes from the fact that sin(x)=-sin(-x) exactly even in finite precision. Whereas finite precision only gives sin(x)~sin(x+2*pi) approximately. Sure it would be nice if quad were smart enough to figure this out, but it really has no way of knowing apriori that the integral over the two intervals you give are equivalent or that the the first is a better result.</p>
2
2009-12-04T18:33:05Z
[ "python", "integration", "scipy", "numerical-methods" ]
Python C-API Object Initialisation
581,281
<p>What is the correct way to initialise a python object into already existing memory (like the inplace new in c++)</p> <p>I tried this code however it causes an access violation with a debug build because the _ob_prev and _ob_next are not set..</p> <pre><code>//PyVarObject *mem; -previously allocated memory Py_INCREF(type); //couldnt get PyObject_HEAD_INIT or PyVarObject_HEAD_INIT to compile //however the macros resolve to this PyVarObject init = {{_PyObject_EXTRA_INIT 1, ((_typeobject*)type)}, 0}; *mem = init; //...other init code for type... </code></pre> <p>The crash occures on line 1519 in object.c</p> <pre><code>void _Py_ForgetReference(register PyObject *op) { #ifdef SLOW_UNREF_CHECK register PyObject *p; #endif if (op-&gt;ob_refcnt &lt; 0) Py_FatalError("UNREF negative refcnt"); if (op == &amp;refchain || op-&gt;_ob_prev-&gt;_ob_next != op || op-&gt;_ob_next-&gt;_ob_prev != op) { //----HERE----// fprintf(stderr, "* ob\n"); _PyObject_Dump(op); fprintf(stderr, "* op-&gt;_ob_prev-&gt;_ob_next\n"); _PyObject_Dump(op-&gt;_ob_prev-&gt;_ob_next); fprintf(stderr, "* op-&gt;_ob_next-&gt;_ob_prev\n"); _PyObject_Dump(op-&gt;_ob_next-&gt;_ob_prev); Py_FatalError("UNREF invalid object"); } #ifdef SLOW_UNREF_CHECK for (p = refchain._ob_next; p != &amp;refchain; p = p-&gt;_ob_next) { if (p == op) break; } if (p == &amp;refchain) /* Not found */ Py_FatalError("UNREF unknown object"); #endif op-&gt;_ob_next-&gt;_ob_prev = op-&gt;_ob_prev; op-&gt;_ob_prev-&gt;_ob_next = op-&gt;_ob_next; op-&gt;_ob_next = op-&gt;_ob_prev = NULL; _Py_INC_TPFREES(op); } </code></pre>
1
2009-02-24T10:43:49Z
588,598
<p>Taking your question at face value, you have a few options. The quick and dirty method is to put an extra Py_INCREF into your initialisation code. Assuming you have no refcount bugs, the refcount will never return to zero, deallocation code will never be called, and there should be no crash. (In fact this may be the way that the statically allocated builtin type objects are managed!)</p> <p>You could write a custom allocator and deallocator for your type that manages memory in your preferred manner. You could in fact write a custom allocator and deallocator for the whole python interpreter.</p> <p>You could manage your python objects in the normal way but store pointers in them to data in the memory you are managing yourself.</p> <p>Looking at the bigger picture... why are you trying to do this?</p> <p>Also, your comments that</p> <blockquote>I tried this code however it causes an access violation with a debug build because the _ob_prev and _ob_next are not set..</blockquote> <p>and </p> <pre><code>//couldnt get PyObject_HEAD_INIT or PyVarObject_HEAD_INIT to compile //however the macros resolve to this</code></pre> <p>are worrying! Have you successfully defined a type which uses standard memory management, before moving on to more advanced stuff?</p>
0
2009-02-26T00:38:03Z
[ "python", "c", "python-3.x", "python-c-api" ]
Python C-API Object Initialisation
581,281
<p>What is the correct way to initialise a python object into already existing memory (like the inplace new in c++)</p> <p>I tried this code however it causes an access violation with a debug build because the _ob_prev and _ob_next are not set..</p> <pre><code>//PyVarObject *mem; -previously allocated memory Py_INCREF(type); //couldnt get PyObject_HEAD_INIT or PyVarObject_HEAD_INIT to compile //however the macros resolve to this PyVarObject init = {{_PyObject_EXTRA_INIT 1, ((_typeobject*)type)}, 0}; *mem = init; //...other init code for type... </code></pre> <p>The crash occures on line 1519 in object.c</p> <pre><code>void _Py_ForgetReference(register PyObject *op) { #ifdef SLOW_UNREF_CHECK register PyObject *p; #endif if (op-&gt;ob_refcnt &lt; 0) Py_FatalError("UNREF negative refcnt"); if (op == &amp;refchain || op-&gt;_ob_prev-&gt;_ob_next != op || op-&gt;_ob_next-&gt;_ob_prev != op) { //----HERE----// fprintf(stderr, "* ob\n"); _PyObject_Dump(op); fprintf(stderr, "* op-&gt;_ob_prev-&gt;_ob_next\n"); _PyObject_Dump(op-&gt;_ob_prev-&gt;_ob_next); fprintf(stderr, "* op-&gt;_ob_next-&gt;_ob_prev\n"); _PyObject_Dump(op-&gt;_ob_next-&gt;_ob_prev); Py_FatalError("UNREF invalid object"); } #ifdef SLOW_UNREF_CHECK for (p = refchain._ob_next; p != &amp;refchain; p = p-&gt;_ob_next) { if (p == op) break; } if (p == &amp;refchain) /* Not found */ Py_FatalError("UNREF unknown object"); #endif op-&gt;_ob_next-&gt;_ob_prev = op-&gt;_ob_prev; op-&gt;_ob_prev-&gt;_ob_next = op-&gt;_ob_next; op-&gt;_ob_next = op-&gt;_ob_prev = NULL; _Py_INC_TPFREES(op); } </code></pre>
1
2009-02-24T10:43:49Z
699,132
<p>You can look at Py_NoneStruct for how this is done. Your code looks basically right.</p> <p>It is a refcounting bug. Statically allocated objects can never be freed, so _Py_ForgetReference should never be called.</p> <p>If you want to be able to free them you must use use a custom allocator instead of static initialization.</p>
0
2009-03-30T21:35:31Z
[ "python", "c", "python-3.x", "python-c-api" ]
Python C-API Object Initialisation
581,281
<p>What is the correct way to initialise a python object into already existing memory (like the inplace new in c++)</p> <p>I tried this code however it causes an access violation with a debug build because the _ob_prev and _ob_next are not set..</p> <pre><code>//PyVarObject *mem; -previously allocated memory Py_INCREF(type); //couldnt get PyObject_HEAD_INIT or PyVarObject_HEAD_INIT to compile //however the macros resolve to this PyVarObject init = {{_PyObject_EXTRA_INIT 1, ((_typeobject*)type)}, 0}; *mem = init; //...other init code for type... </code></pre> <p>The crash occures on line 1519 in object.c</p> <pre><code>void _Py_ForgetReference(register PyObject *op) { #ifdef SLOW_UNREF_CHECK register PyObject *p; #endif if (op-&gt;ob_refcnt &lt; 0) Py_FatalError("UNREF negative refcnt"); if (op == &amp;refchain || op-&gt;_ob_prev-&gt;_ob_next != op || op-&gt;_ob_next-&gt;_ob_prev != op) { //----HERE----// fprintf(stderr, "* ob\n"); _PyObject_Dump(op); fprintf(stderr, "* op-&gt;_ob_prev-&gt;_ob_next\n"); _PyObject_Dump(op-&gt;_ob_prev-&gt;_ob_next); fprintf(stderr, "* op-&gt;_ob_next-&gt;_ob_prev\n"); _PyObject_Dump(op-&gt;_ob_next-&gt;_ob_prev); Py_FatalError("UNREF invalid object"); } #ifdef SLOW_UNREF_CHECK for (p = refchain._ob_next; p != &amp;refchain; p = p-&gt;_ob_next) { if (p == op) break; } if (p == &amp;refchain) /* Not found */ Py_FatalError("UNREF unknown object"); #endif op-&gt;_ob_next-&gt;_ob_prev = op-&gt;_ob_prev; op-&gt;_ob_prev-&gt;_ob_next = op-&gt;_ob_next; op-&gt;_ob_next = op-&gt;_ob_prev = NULL; _Py_INC_TPFREES(op); } </code></pre>
1
2009-02-24T10:43:49Z
1,964,895
<p>What are doing is pretty horrible. Unless this code path is really performance critical I'd advise you to allocate your objects on the heap as is normally done.</p>
1
2009-12-27T01:32:02Z
[ "python", "c", "python-3.x", "python-c-api" ]
Similar to Pass in Python for C#
581,343
<p>In python we can .. </p> <pre><code>a = 5 if a == 5: pass #Do Nothing else: print "Hello World" </code></pre> <p>I wonder if it a similar way to do this in C#</p>
12
2009-02-24T11:00:30Z
581,348
<p>Use empty braces.</p> <pre><code>int a = 5; if (a == 5) {} else { Console.Write("Hello World"); } </code></pre>
16
2009-02-24T11:03:27Z
[ "c#", "python" ]
Similar to Pass in Python for C#
581,343
<p>In python we can .. </p> <pre><code>a = 5 if a == 5: pass #Do Nothing else: print "Hello World" </code></pre> <p>I wonder if it a similar way to do this in C#</p>
12
2009-02-24T11:00:30Z
581,350
<p>Empty block: </p> <pre><code>{} </code></pre>
6
2009-02-24T11:03:58Z
[ "c#", "python" ]
Similar to Pass in Python for C#
581,343
<p>In python we can .. </p> <pre><code>a = 5 if a == 5: pass #Do Nothing else: print "Hello World" </code></pre> <p>I wonder if it a similar way to do this in C#</p>
12
2009-02-24T11:00:30Z
581,357
<p>Why not just say:</p> <pre><code>if (a != 5) { Console.Write("Hello World"); } </code></pre>
11
2009-02-24T11:05:56Z
[ "c#", "python" ]
Similar to Pass in Python for C#
581,343
<p>In python we can .. </p> <pre><code>a = 5 if a == 5: pass #Do Nothing else: print "Hello World" </code></pre> <p>I wonder if it a similar way to do this in C#</p>
12
2009-02-24T11:00:30Z
581,359
<p>Either use an empty block as suggested in other answers, or reverse the condition:</p> <pre><code>if (a != 5) { Console.WriteLine("Hello world"); } </code></pre> <p>or more mechanically:</p> <pre><code>if (!(a == 5)) { Console.WriteLine("Hello world"); } </code></pre>
3
2009-02-24T11:06:48Z
[ "c#", "python" ]
Similar to Pass in Python for C#
581,343
<p>In python we can .. </p> <pre><code>a = 5 if a == 5: pass #Do Nothing else: print "Hello World" </code></pre> <p>I wonder if it a similar way to do this in C#</p>
12
2009-02-24T11:00:30Z
581,361
<p>A better question would be why you would want to do such a thing. If you're not planning on doing anything then leave it out, rather.</p> <pre><code>int a = 5; if (a != 5) { Console.Write("Hello World"); } </code></pre>
1
2009-02-24T11:07:57Z
[ "c#", "python" ]
Similar to Pass in Python for C#
581,343
<p>In python we can .. </p> <pre><code>a = 5 if a == 5: pass #Do Nothing else: print "Hello World" </code></pre> <p>I wonder if it a similar way to do this in C#</p>
12
2009-02-24T11:00:30Z
581,365
<p>Is <code>pass</code> used in the context of a loop? If so, use the <code>continue</code> statement:</p> <pre><code>for (var i = 0; i &lt; 10; ++i) { if (i == 5) { continue; } Console.WriteLine("Hello World"); } </code></pre>
4
2009-02-24T11:10:15Z
[ "c#", "python" ]
In Python, how do I make a temp file that persists until the next run?
581,851
<p>I need to create a folder that I use only once, but need to have it exist until the next run. It seems like I should be using the tmp_file module in the standard library, but I'm not sure how to get the behavior that I want. </p> <p>Currently, I'm doing the following to create the directory: </p> <pre><code>randName = "temp" + str(random.randint(1000, 9999)) os.makedirs(randName) </code></pre> <p>And when I want to delete the directory, I just look for a directory with "temp" in it.<br /> This seems like a dirty hack, but I'm not sure of a better way at the moment. </p> <p>Incidentally, the reason that I need the folder around is that I start a process that uses the folder with the following: </p> <pre><code>subprocess.Popen([command], shell=True).pid </code></pre> <p>and then quit my script to let the other process finish the work.</p>
3
2009-02-24T14:03:26Z
581,879
<p>A temporary file is something that lasts for a single program run.</p> <p>What you need is not, therefore, a temporary file.</p> <p>Also, beware of multiple users on a single machine - just deleting anything with the 'temp' pattern could be anti-social, doubly so if the directory is not located securely out of the way.</p> <p>Also, remember that on some machines, the <code>/tmp</code> file system is rebuilt when the machine reboots.</p>
3
2009-02-24T14:12:06Z
[ "python", "temporary-files" ]
In Python, how do I make a temp file that persists until the next run?
581,851
<p>I need to create a folder that I use only once, but need to have it exist until the next run. It seems like I should be using the tmp_file module in the standard library, but I'm not sure how to get the behavior that I want. </p> <p>Currently, I'm doing the following to create the directory: </p> <pre><code>randName = "temp" + str(random.randint(1000, 9999)) os.makedirs(randName) </code></pre> <p>And when I want to delete the directory, I just look for a directory with "temp" in it.<br /> This seems like a dirty hack, but I'm not sure of a better way at the moment. </p> <p>Incidentally, the reason that I need the folder around is that I start a process that uses the folder with the following: </p> <pre><code>subprocess.Popen([command], shell=True).pid </code></pre> <p>and then quit my script to let the other process finish the work.</p>
3
2009-02-24T14:03:26Z
581,902
<p>Creating the folder with a 4-digit random number is insecure, and you also need to worry about collisions with other instances of your program. </p> <p>A much better way is to create the folder using <a href="http://docs.python.org/library/tempfile.html"><code>tempfile.mkdtemp</code></a>, which does exactly what you want (i.e. the folder is not deleted when your script exits). You would then pass the folder name to the second Popen'ed script as an argument, and it would be responsible for deleting it.</p>
16
2009-02-24T14:18:50Z
[ "python", "temporary-files" ]
In Python, how do I make a temp file that persists until the next run?
581,851
<p>I need to create a folder that I use only once, but need to have it exist until the next run. It seems like I should be using the tmp_file module in the standard library, but I'm not sure how to get the behavior that I want. </p> <p>Currently, I'm doing the following to create the directory: </p> <pre><code>randName = "temp" + str(random.randint(1000, 9999)) os.makedirs(randName) </code></pre> <p>And when I want to delete the directory, I just look for a directory with "temp" in it.<br /> This seems like a dirty hack, but I'm not sure of a better way at the moment. </p> <p>Incidentally, the reason that I need the folder around is that I start a process that uses the folder with the following: </p> <pre><code>subprocess.Popen([command], shell=True).pid </code></pre> <p>and then quit my script to let the other process finish the work.</p>
3
2009-02-24T14:03:26Z
581,905
<p><code>tempfile</code> is just fine, but to be on a safe side you'd need to safe a directory name somewhere until the next run, for example pickle it. then read it in the next run and delete directory. and you are not required to have <code>/tmp</code> for the root, <code>tempfile.mkdtemp</code> has an optional <code>dir</code> parameter for that. by and large, though, it won't be different from what you're doing at the moment.</p>
1
2009-02-24T14:19:27Z
[ "python", "temporary-files" ]
In Python, how do I make a temp file that persists until the next run?
581,851
<p>I need to create a folder that I use only once, but need to have it exist until the next run. It seems like I should be using the tmp_file module in the standard library, but I'm not sure how to get the behavior that I want. </p> <p>Currently, I'm doing the following to create the directory: </p> <pre><code>randName = "temp" + str(random.randint(1000, 9999)) os.makedirs(randName) </code></pre> <p>And when I want to delete the directory, I just look for a directory with "temp" in it.<br /> This seems like a dirty hack, but I'm not sure of a better way at the moment. </p> <p>Incidentally, the reason that I need the folder around is that I start a process that uses the folder with the following: </p> <pre><code>subprocess.Popen([command], shell=True).pid </code></pre> <p>and then quit my script to let the other process finish the work.</p>
3
2009-02-24T14:03:26Z
581,972
<p>"I need to create a folder that I use only once, but need to have it exist until the next run."</p> <p>"Incidentally, the reason that I need the folder around is that I start a process ..."</p> <p>Not incidental, at all. Crucial.</p> <p>It appears you have the following design pattern.</p> <pre><code>mkdir someDirectory proc1 -o someDirectory # Write to the directory proc2 -i someDirectory # Read from the directory if [ %? == 0 ] then rm someDirectory fi </code></pre> <p>Is that the kind of thing you'd write at the shell level?</p> <p>If so, consider breaking your Python application into to several parts.</p> <ul> <li><p>The parts that do the real work ("proc1" and "proc2") </p></li> <li><p>A Shell which manages the resources and processes; essentially a Python replacement for a bash script.</p></li> </ul>
4
2009-02-24T14:40:04Z
[ "python", "temporary-files" ]
In Python, how do I make a temp file that persists until the next run?
581,851
<p>I need to create a folder that I use only once, but need to have it exist until the next run. It seems like I should be using the tmp_file module in the standard library, but I'm not sure how to get the behavior that I want. </p> <p>Currently, I'm doing the following to create the directory: </p> <pre><code>randName = "temp" + str(random.randint(1000, 9999)) os.makedirs(randName) </code></pre> <p>And when I want to delete the directory, I just look for a directory with "temp" in it.<br /> This seems like a dirty hack, but I'm not sure of a better way at the moment. </p> <p>Incidentally, the reason that I need the folder around is that I start a process that uses the folder with the following: </p> <pre><code>subprocess.Popen([command], shell=True).pid </code></pre> <p>and then quit my script to let the other process finish the work.</p>
3
2009-02-24T14:03:26Z
582,243
<p>What you've suggested is dangerous. You may have race conditions if anyone else is trying to create those directories -- including other instances of your application. Also, deleting anything containing "temp" may result in deleting more than you intended. As others have mentioned, <a href="http://docs.python.org/library/tempfile.html#tempfile.mkdtemp">tempfile.mkdtemp</a> is probably the safest way to go. Here is an example of what you've described, including launching a subprocess to use the new directory.</p> <pre><code>import tempfile import shutil import subprocess d = tempfile.mkdtemp(prefix='tmp') try: subprocess.check_call(['/bin/echo', 'Directory:', d]) finally: shutil.rmtree(d) </code></pre>
8
2009-02-24T15:43:23Z
[ "python", "temporary-files" ]
In Python, how do I make a temp file that persists until the next run?
581,851
<p>I need to create a folder that I use only once, but need to have it exist until the next run. It seems like I should be using the tmp_file module in the standard library, but I'm not sure how to get the behavior that I want. </p> <p>Currently, I'm doing the following to create the directory: </p> <pre><code>randName = "temp" + str(random.randint(1000, 9999)) os.makedirs(randName) </code></pre> <p>And when I want to delete the directory, I just look for a directory with "temp" in it.<br /> This seems like a dirty hack, but I'm not sure of a better way at the moment. </p> <p>Incidentally, the reason that I need the folder around is that I start a process that uses the folder with the following: </p> <pre><code>subprocess.Popen([command], shell=True).pid </code></pre> <p>and then quit my script to let the other process finish the work.</p>
3
2009-02-24T14:03:26Z
1,414,419
<p>The best way of creating the temporary file name is either using tempName.TemporaryFile(mode='w+b', suffix='.tmp', prifix='someRandomNumber' dir=None) or u can use mktemp() function.</p> <p>The mktemp() function will not actually create any file, but will provide a unique filename (actually does not contain PID). </p>
1
2009-09-12T06:00:59Z
[ "python", "temporary-files" ]
In Python, how do I make a temp file that persists until the next run?
581,851
<p>I need to create a folder that I use only once, but need to have it exist until the next run. It seems like I should be using the tmp_file module in the standard library, but I'm not sure how to get the behavior that I want. </p> <p>Currently, I'm doing the following to create the directory: </p> <pre><code>randName = "temp" + str(random.randint(1000, 9999)) os.makedirs(randName) </code></pre> <p>And when I want to delete the directory, I just look for a directory with "temp" in it.<br /> This seems like a dirty hack, but I'm not sure of a better way at the moment. </p> <p>Incidentally, the reason that I need the folder around is that I start a process that uses the folder with the following: </p> <pre><code>subprocess.Popen([command], shell=True).pid </code></pre> <p>and then quit my script to let the other process finish the work.</p>
3
2009-02-24T14:03:26Z
4,330,740
<p>You can also automatically register an function to completely remove the temporary directory on any exit (with or without error) by doing :</p> <pre><code>import atexit import shutil import tempfile # create your temporary directory d = tempfile.mkdtemp() # suppress it when python will be closed atexit.register(lambda: shutil.rmtree(d)) # do your stuff... subprocess.Popen([command], shell=True).pid </code></pre>
2
2010-12-02T01:04:20Z
[ "python", "temporary-files" ]
How can you profile a Python script?
582,336
<p>Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p> <p>What is a good way to profile how long a python program takes to run?</p>
702
2009-02-24T16:01:26Z
582,337
<p>Python includes a profiler called cProfile. It not only gives the total running time, but also times each function separately, and tells you how many times each function was called, making it easy to determine where you should make optimizations.</p> <p>You can call it from within your code, or from the interpreter, like this:</p> <pre><code>import cProfile cProfile.run('foo()') </code></pre> <p>Even more usefully, you can invoke the cProfile when running a script:</p> <pre><code>python -m cProfile myscript.py </code></pre> <p>To make it even easier, I made a little batch file called 'profile.bat':</p> <pre><code>python -m cProfile %1 </code></pre> <p>So all I have to do is run:</p> <pre><code>profile euler048.py </code></pre> <p>And I get this:</p> <pre><code>1007 function calls in 0.061 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.061 0.061 &lt;string&gt;:1(&lt;module&gt;) 1000 0.051 0.000 0.051 0.000 euler048.py:2(&lt;lambda&gt;) 1 0.005 0.005 0.061 0.061 euler048.py:2(&lt;module&gt;) 1 0.000 0.000 0.061 0.061 {execfile} 1 0.002 0.002 0.053 0.053 {map} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler objects} 1 0.000 0.000 0.000 0.000 {range} 1 0.003 0.003 0.003 0.003 {sum} </code></pre> <p>EDIT: Updated link to a good video resource from PyCon 2013: <a href="http://lanyrd.com/2013/pycon/scdywg/">http://lanyrd.com/2013/pycon/scdywg/</a></p>
755
2009-02-24T16:01:40Z
[ "python", "performance", "profiling", "time-complexity" ]