title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
Django - How to do tuple unpacking in a template 'for' loop
271,077
<p>In my views.py, I'm building a list of two-tuples, where the second item in the tuple is another list, like this:</p> <pre><code>[ Product_Type_1, [ product_1, product_2 ], Product_Type_2, [ product_3, product_4 ]] </code></pre> <p>In plain old Python, I could iteration the list like this:</p> <pre><code>for product_type, products in list: print product_type for product in products: print product </code></pre> <p>I can't seem to do the same thing in my Django template:</p> <pre><code>{% for product_type, products in product_list %} print product_type {% for product in products %} print product {% endfor %} {% endfor %} </code></pre> <p>I get this error from Django:</p> <p><strong>Caught an exception while rendering: zip argument #2 must support iteration</strong></p> <p>Of course, there is some HTML markup in the template, not print statements. Is tuple unpacking not supported in the Django template language? Or am I going about this the wrong way? All I am trying to do is display a simple hierarchy of objects - there are several product types, each with several products (in models.py, Product has a foreign key to Product_type, a simple one-to-many relationship).</p> <p>Obviously, I am quite new to Django, so any input would be appreciated.</p>
41
2008-11-07T02:40:20Z
271,098
<p>Just send the template a list of product types and do something like:</p> <pre><code>{% for product_type in product_type_list %} {{ product_type }} {% for product in product_type.products.all %} {{ product }} {% endfor %} {% endfor %} </code></pre> <p>It's been a little while so I can't remember exactly what the syntax is, let me know if that works. Check the <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#related-objects" rel="nofollow">documentation</a>.</p>
2
2008-11-07T02:47:41Z
[ "python", "django", "templates", "tuples", "iterable-unpacking" ]
Django - How to do tuple unpacking in a template 'for' loop
271,077
<p>In my views.py, I'm building a list of two-tuples, where the second item in the tuple is another list, like this:</p> <pre><code>[ Product_Type_1, [ product_1, product_2 ], Product_Type_2, [ product_3, product_4 ]] </code></pre> <p>In plain old Python, I could iteration the list like this:</p> <pre><code>for product_type, products in list: print product_type for product in products: print product </code></pre> <p>I can't seem to do the same thing in my Django template:</p> <pre><code>{% for product_type, products in product_list %} print product_type {% for product in products %} print product {% endfor %} {% endfor %} </code></pre> <p>I get this error from Django:</p> <p><strong>Caught an exception while rendering: zip argument #2 must support iteration</strong></p> <p>Of course, there is some HTML markup in the template, not print statements. Is tuple unpacking not supported in the Django template language? Or am I going about this the wrong way? All I am trying to do is display a simple hierarchy of objects - there are several product types, each with several products (in models.py, Product has a foreign key to Product_type, a simple one-to-many relationship).</p> <p>Obviously, I am quite new to Django, so any input would be appreciated.</p>
41
2008-11-07T02:40:20Z
271,128
<p>it would be best if you construct your data like {note the '(' and ')' can be exchanged for '[' and ']' repectively, one being for tuples, one for lists}</p> <pre><code>[ (Product_Type_1, ( product_1, product_2 )), (Product_Type_2, ( product_3, product_4 )) ] </code></pre> <p>and have the template do this:</p> <pre><code>{% for product_type, products in product_type_list %} {{ product_type }} {% for product in products %} {{ product }} {% endfor %} {% endfor %} </code></pre> <p>the way tuples/lists are unpacked in for loops is based on the item returned by the list iterator. each iteration only one item was returned. the first time around the loop, Product_Type_1, the second your list of products... </p>
50
2008-11-07T03:11:51Z
[ "python", "django", "templates", "tuples", "iterable-unpacking" ]
Django - How to do tuple unpacking in a template 'for' loop
271,077
<p>In my views.py, I'm building a list of two-tuples, where the second item in the tuple is another list, like this:</p> <pre><code>[ Product_Type_1, [ product_1, product_2 ], Product_Type_2, [ product_3, product_4 ]] </code></pre> <p>In plain old Python, I could iteration the list like this:</p> <pre><code>for product_type, products in list: print product_type for product in products: print product </code></pre> <p>I can't seem to do the same thing in my Django template:</p> <pre><code>{% for product_type, products in product_list %} print product_type {% for product in products %} print product {% endfor %} {% endfor %} </code></pre> <p>I get this error from Django:</p> <p><strong>Caught an exception while rendering: zip argument #2 must support iteration</strong></p> <p>Of course, there is some HTML markup in the template, not print statements. Is tuple unpacking not supported in the Django template language? Or am I going about this the wrong way? All I am trying to do is display a simple hierarchy of objects - there are several product types, each with several products (in models.py, Product has a foreign key to Product_type, a simple one-to-many relationship).</p> <p>Obviously, I am quite new to Django, so any input would be appreciated.</p>
41
2008-11-07T02:40:20Z
1,168,438
<p>You must used this way:</p> <pre><code>{% for product_type, products in product_list.items %} print product_type {% for product in products %} print product {% endfor %} {% endfor %} </code></pre> <p>Don't forget the variable items in the dictionary data</p>
3
2009-07-22T21:41:13Z
[ "python", "django", "templates", "tuples", "iterable-unpacking" ]
Django - How to do tuple unpacking in a template 'for' loop
271,077
<p>In my views.py, I'm building a list of two-tuples, where the second item in the tuple is another list, like this:</p> <pre><code>[ Product_Type_1, [ product_1, product_2 ], Product_Type_2, [ product_3, product_4 ]] </code></pre> <p>In plain old Python, I could iteration the list like this:</p> <pre><code>for product_type, products in list: print product_type for product in products: print product </code></pre> <p>I can't seem to do the same thing in my Django template:</p> <pre><code>{% for product_type, products in product_list %} print product_type {% for product in products %} print product {% endfor %} {% endfor %} </code></pre> <p>I get this error from Django:</p> <p><strong>Caught an exception while rendering: zip argument #2 must support iteration</strong></p> <p>Of course, there is some HTML markup in the template, not print statements. Is tuple unpacking not supported in the Django template language? Or am I going about this the wrong way? All I am trying to do is display a simple hierarchy of objects - there are several product types, each with several products (in models.py, Product has a foreign key to Product_type, a simple one-to-many relationship).</p> <p>Obviously, I am quite new to Django, so any input would be appreciated.</p>
41
2008-11-07T02:40:20Z
4,756,748
<p>Another way is as follows. </p> <p>If one has a list of tuples say</p> <pre><code>mylst = [(a, b, c), (x, y, z), (l, m, n)], </code></pre> <p>then one can unpack this list in the template file in the following manner. In my case I had a list of tuples which contained the URL, title, and summary of a document.</p> <pre><code>{\% for item in mylst \%} {{ item.0 }} {{ item.1}} {{ item.2 }} {\% endfor \%} </code></pre>
48
2011-01-21T08:23:38Z
[ "python", "django", "templates", "tuples", "iterable-unpacking" ]
Django - How to do tuple unpacking in a template 'for' loop
271,077
<p>In my views.py, I'm building a list of two-tuples, where the second item in the tuple is another list, like this:</p> <pre><code>[ Product_Type_1, [ product_1, product_2 ], Product_Type_2, [ product_3, product_4 ]] </code></pre> <p>In plain old Python, I could iteration the list like this:</p> <pre><code>for product_type, products in list: print product_type for product in products: print product </code></pre> <p>I can't seem to do the same thing in my Django template:</p> <pre><code>{% for product_type, products in product_list %} print product_type {% for product in products %} print product {% endfor %} {% endfor %} </code></pre> <p>I get this error from Django:</p> <p><strong>Caught an exception while rendering: zip argument #2 must support iteration</strong></p> <p>Of course, there is some HTML markup in the template, not print statements. Is tuple unpacking not supported in the Django template language? Or am I going about this the wrong way? All I am trying to do is display a simple hierarchy of objects - there are several product types, each with several products (in models.py, Product has a foreign key to Product_type, a simple one-to-many relationship).</p> <p>Obviously, I am quite new to Django, so any input would be appreciated.</p>
41
2008-11-07T02:40:20Z
35,512,819
<p>If you have a fixed number in your tuples, you could just use indexing. I needed to mix a dictionary and the values were tuples, so I did this:</p> <p>In the view:</p> <pre><code>my_dict = {'parrot': ('dead', 'stone'), 'lumberjack': ('sleep_all_night', 'work_all_day')} </code></pre> <p>In the template:</p> <pre><code>&lt;select&gt; {% for key, tuple in my_dict.items %} &lt;option value="{{ key }}" important-attr="{{ tuple.0 }}"&gt;{{ tuple.1 }}&lt;/option&gt; {% endfor %} &lt;/select&gt; </code></pre>
0
2016-02-19T18:53:19Z
[ "python", "django", "templates", "tuples", "iterable-unpacking" ]
How does one add default (hidden) values to form templates in Django?
271,244
<p>Given a Django.db models class:</p> <pre><code>class P(models.Model): type = models.ForeignKey(Type) # Type is another models.Model class name = models.CharField() </code></pre> <p>where one wishes to create a new P with a specified type, i.e. how does one make "type" to be a default, hidden field (from the user), where type is given likeso:</p> <pre><code>http://x.y/P/new?type=3 </code></pre> <p>So that in the form no "type" field will appear, but when the P is saved, its type will have id 3 (i.e. Type.objects.get(pk=3)).</p> <p>Secondarily, how does one (&amp; is it possible) specify a "default" type in the url, via urls.py, when using generic Django views, viz.</p> <pre><code>urlpatterns = ('django.generic.views.create_update', url(r'^/new$', 'create_object', { 'model': P }, name='new_P'), ) </code></pre> <p>I found that terribly difficult to describe, which may be part of the problem. :) Input is much appreciated!</p>
7
2008-11-07T04:27:14Z
271,252
<p>To have a default Foreign Key in a model:</p> <pre><code>mydefault = Type.objects.get(pk=3) class P(models.Model): type = models.ForeignKey(Type, default=mydefault) # Type is another models.Model class name = models.CharField() </code></pre> <p>Note that using <code>pk=x</code> is pretty ugly, as ideally you shouldn't care what the primary key is equal to. Try to get to the object you want by some other attribute.</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#notes-on-capturing-text-in-urls" rel="nofollow">Here</a>'s how you put defaults in your urls:</p> <pre><code># URLconf urlpatterns = patterns('', (r'^blog/$', 'blog.views.page'), (r'^blog/page(?P&lt;num&gt;\d+)/$', 'blog.views.page'), ) # View (in blog/views.py) def page(request, num="1"): # Output the appropriate page of blog entries, according to num. </code></pre> <blockquote> <p>In the above example, both URL patterns point to the same view -- blog.views.page -- but the first pattern doesn't capture anything from the URL. If the first pattern matches, the page() function will use its default argument for num, "1". If the second pattern matches, page() will use whatever num value was captured by the regex.</p> </blockquote>
5
2008-11-07T04:32:23Z
[ "python", "django", "django-templates", "django-urls" ]
How does one add default (hidden) values to form templates in Django?
271,244
<p>Given a Django.db models class:</p> <pre><code>class P(models.Model): type = models.ForeignKey(Type) # Type is another models.Model class name = models.CharField() </code></pre> <p>where one wishes to create a new P with a specified type, i.e. how does one make "type" to be a default, hidden field (from the user), where type is given likeso:</p> <pre><code>http://x.y/P/new?type=3 </code></pre> <p>So that in the form no "type" field will appear, but when the P is saved, its type will have id 3 (i.e. Type.objects.get(pk=3)).</p> <p>Secondarily, how does one (&amp; is it possible) specify a "default" type in the url, via urls.py, when using generic Django views, viz.</p> <pre><code>urlpatterns = ('django.generic.views.create_update', url(r'^/new$', 'create_object', { 'model': P }, name='new_P'), ) </code></pre> <p>I found that terribly difficult to describe, which may be part of the problem. :) Input is much appreciated!</p>
7
2008-11-07T04:27:14Z
271,303
<p>The widget <code>django.forms.widgets.HiddenInput</code> will render your field as hidden.</p> <p>In most cases, I think you'll find that any hidden form value could also be specified as a url parameter instead. In other words:</p> <pre><code>&lt;form action="new/{{your_hidden_value}}" method="post"&gt; .... &lt;/form&gt; </code></pre> <p>and in urls.py:</p> <pre><code>^/new/(?P&lt;hidden_value&gt;\w+)/ </code></pre> <p>I prefer this technique myself because I only really find myself needing hidden form fields when I need to track the primary key of a model instance - in which case an "edit/pkey" url serves the purposes of both initiating the edit/returning the form, and receiving the POST on save.</p>
8
2008-11-07T05:26:25Z
[ "python", "django", "django-templates", "django-urls" ]
How does one add default (hidden) values to form templates in Django?
271,244
<p>Given a Django.db models class:</p> <pre><code>class P(models.Model): type = models.ForeignKey(Type) # Type is another models.Model class name = models.CharField() </code></pre> <p>where one wishes to create a new P with a specified type, i.e. how does one make "type" to be a default, hidden field (from the user), where type is given likeso:</p> <pre><code>http://x.y/P/new?type=3 </code></pre> <p>So that in the form no "type" field will appear, but when the P is saved, its type will have id 3 (i.e. Type.objects.get(pk=3)).</p> <p>Secondarily, how does one (&amp; is it possible) specify a "default" type in the url, via urls.py, when using generic Django views, viz.</p> <pre><code>urlpatterns = ('django.generic.views.create_update', url(r'^/new$', 'create_object', { 'model': P }, name='new_P'), ) </code></pre> <p>I found that terribly difficult to describe, which may be part of the problem. :) Input is much appreciated!</p>
7
2008-11-07T04:27:14Z
1,937,451
<p>If you go with Andrew's approach of including the hidden value in the url and still want to use one of Django's built in form templates, there are ways for you to exclude the hidden field.</p> <p><a href="http://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#using-a-subset-of-fields-on-the-form" rel="nofollow">http://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#using-a-subset-of-fields-on-the-form</a></p>
2
2009-12-20T23:16:18Z
[ "python", "django", "django-templates", "django-urls" ]
Linking languages
271,488
<p>I asked <a href="http://stackoverflow.com/questions/269417/which-language-should-i-use">a question</a> earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. </p> <p>So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better?</p> <p>My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!</p>
15
2008-11-07T08:07:10Z
271,494
<p>It may be a good approach to start with a script, and call a compilation-based language from that script only for more advanced needs.</p> <p>For instance, <a href="http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html" rel="nofollow">calling java from ruby script</a> works quite well.</p> <pre><code>require "java" # The next line exposes Java's String as JString include_class("java.lang.String") { |pkg, name| "J" + name } s = JString.new("f") </code></pre>
2
2008-11-07T08:11:45Z
[ "java", "c++", "python", "ruby", "perl" ]
Linking languages
271,488
<p>I asked <a href="http://stackoverflow.com/questions/269417/which-language-should-i-use">a question</a> earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. </p> <p>So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better?</p> <p>My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!</p>
15
2008-11-07T08:07:10Z
271,501
<p>You can build your program in one of the higher level languages for example Python or Ruby and then call modules that are compiled in the lower level language for the parts you need performance. You can choose a platform depending on the lower level language you want.</p> <p>For example if you want to do C++ for the speedy stuff you can just use plain Python or Ruby and call DLLs compiled in C++. If you want to use Java you can use Jython or one of the other dynamic languages on the Java platform to call the Java code this is easier than the C++ route because you've got a common virtual machine so a Java object can be used directly in Jython or JRuby. The same can be done on the .Net platform with the Iron-languages and C# although you seem to have more experience with C++ and Java so those would be better options.</p>
2
2008-11-07T08:17:10Z
[ "java", "c++", "python", "ruby", "perl" ]
Linking languages
271,488
<p>I asked <a href="http://stackoverflow.com/questions/269417/which-language-should-i-use">a question</a> earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. </p> <p>So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better?</p> <p>My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!</p>
15
2008-11-07T08:07:10Z
271,590
<p>First, a meta comment: I would highly recommend coding the entire thing in a high-level language, profiling like mad, and optimizing only where profiling shows it's necessary. First optimize the algorithm, then the code, then think about bringing in the heavy iron. Having an optimum algorithm and clean code will make things much easier when/if you need to reimplement in a lower-level language.</p> <p>Speaking for Python, <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython">IronPython</a>/C# is probably the easiest optimization path. </p> <p>CPython with C++ is doable, but I find C a lot easier to handle (but not all that easy, being C). Two tools that ease this are <a href="http://cython.org/">cython</a>/<a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/">pyrex</a> (for C) and <a href="http://shed-skin.blogspot.com/">shedskin</a> (for C++). These compile Python into C/C++, and from there you can access C/C++ libraries without too much ado.</p> <p>I've never used jython, but I hear that the jython/Java optimization path isn't all that bad.</p>
9
2008-11-07T09:14:32Z
[ "java", "c++", "python", "ruby", "perl" ]
Linking languages
271,488
<p>I asked <a href="http://stackoverflow.com/questions/269417/which-language-should-i-use">a question</a> earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. </p> <p>So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better?</p> <p>My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!</p>
15
2008-11-07T08:07:10Z
271,642
<p><a href="http://www.boost.org/doc/libs/1_36_0/libs/python/doc/tutorial/doc/html/index.html">Boost.Python</a> provides an easy way to turn C++ code into Python modules. It's rather mature and works well in my experience. </p> <p>For example, the inevitable Hello World...</p> <pre><code>char const* greet() { return "hello, world"; } </code></pre> <p>can be exposed to Python by writing a Boost.Python wrapper:</p> <pre><code>#include &lt;boost/python.hpp&gt; BOOST_PYTHON_MODULE(hello_ext) { using namespace boost::python; def("greet", greet); } </code></pre> <p>That's it. We're done. We can now build this as a shared library. The resulting DLL is now visible to Python. Here's a sample Python session:</p> <pre><code>&gt;&gt;&gt; import hello_ext &gt;&gt;&gt; print hello.greet() hello, world </code></pre> <p>(example taken from boost.org)</p>
14
2008-11-07T09:46:13Z
[ "java", "c++", "python", "ruby", "perl" ]
Linking languages
271,488
<p>I asked <a href="http://stackoverflow.com/questions/269417/which-language-should-i-use">a question</a> earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. </p> <p>So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better?</p> <p>My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!</p>
15
2008-11-07T08:07:10Z
271,729
<p>I agree with the Idea of coding first in a high level language such as Python, Profiling and then Implementing any code that needs speeding up in C / C++ and wrapping it for use in the high level language.</p> <p>As an alternative to boost I would like to suggest <a href="http://www.swig.org/">SWIG</a> for creating Python callable code from C. Its reasonably painless to use, and will compile callable modules for a wide range of languages. (Python, Ruby, Java, Lua. to name a few) from C code.</p> <p>The wrapping process is semi automated, so there is no need to add new functions to the base C code, making a smoother work flow. </p>
6
2008-11-07T10:42:10Z
[ "java", "c++", "python", "ruby", "perl" ]
Linking languages
271,488
<p>I asked <a href="http://stackoverflow.com/questions/269417/which-language-should-i-use">a question</a> earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. </p> <p>So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better?</p> <p>My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!</p>
15
2008-11-07T08:07:10Z
272,163
<p>Perl has several ways to use other languages. Look at the <a href="http://search.cpan.org/perldoc?Inline" rel="nofollow">Inline::<em></a> family of modules on CPAN. Following the advice from others in this question, I'd write the whole thing in a single dynamic language (Perl, Python, Ruby, etc) and then optimize the bits that need it. With Perl and Inline::</em> you can optimize in C, C++, or Java. Or you could look at <a href="http://search.cpan.org/perldoc?AI::Prolog" rel="nofollow">AI::Prolog</a> which allows you to embed Prolog for AI/Logic programming.</p>
4
2008-11-07T14:10:07Z
[ "java", "c++", "python", "ruby", "perl" ]
Linking languages
271,488
<p>I asked <a href="http://stackoverflow.com/questions/269417/which-language-should-i-use">a question</a> earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. </p> <p>So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better?</p> <p>My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!</p>
15
2008-11-07T08:07:10Z
272,363
<p>If you choose Perl there are plenty of resources for interfacing other languages.</p> <p><a href="http://search.cpan.org/dist/Inline/C/C.podI" rel="nofollow">Inline::C</a><br> <a href="http://search.cpan.org/dist/Inline-CPP/" rel="nofollow">Inline::CPP</a><br> <a href="http://search.cpan.org/dist/Inline-Java/Java.pod" rel="nofollow">Inline::Java</a></p> <p>From <a href="http://search.cpan.org/dist/Inline/C/C-Cookbook.pod" rel="nofollow">Inline::C-Cookbook</a>:</p> <pre><code>use Inline C =&gt; &lt;&lt;'END_C'; void greet() { printf("Hello, world\n"); } END_C greet; </code></pre> <hr> <p>With Perl 6 it gets even easier to import subroutine from native library code using <a href="https://doc.perl6.org/language/nativecall" rel="nofollow">NativeCall</a>.</p> <pre class="lang-perl6 prettyprint-override"><code>use v6.c; sub c-print ( Str() $s ){ use NativeCall; # restrict the function to inside of this subroutine because printf is # vararg based, and we only handle '%s' based inputs here # it should be possible to handle more but it requires generating # a Signature object based on the format string and then do a # nativecast with that Signature, and a pointer to printf sub printf ( str, str --&gt; int32 ) is native('libc:6') {} printf '%s', $s } c-print 'Hello World'; </code></pre> <p>This is just a simple example, you can create a class that has a representation of a Pointer, and have some of the methods be C code from the library you are using. ( only works if the first argument of the C code is the pointer, otherwise you would have to wrap it )</p> <p>If you need the Perl 6 subroutine/method name to be different you can use the <code>is symbol</code> trait modifier.</p> <p>There are also Inline modules for Perl 6 as well.</p>
5
2008-11-07T15:11:13Z
[ "java", "c++", "python", "ruby", "perl" ]
Linking languages
271,488
<p>I asked <a href="http://stackoverflow.com/questions/269417/which-language-should-i-use">a question</a> earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. </p> <p>So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better?</p> <p>My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!</p>
15
2008-11-07T08:07:10Z
276,021
<p>I have a different perspective, having had lots of luck with integrating C++ and Python for some real time live video image processing.</p> <p>I would say you should match the language to the task for each module. If you're responding to a network, do it in Python, Python can keep up with network traffic just fine. UI: Python, People are slow, and Python is great for UIs using wxPython or PyObjC on Mac, or PyGTK. If you're doing math on lots of data, or signal processing, or image processing... code it in C or C++ with unit tests, then use <strong>SWIG</strong> to create the binding to any higher level language.</p> <p>I used the image libraries in wxWidgets in my C++, which are already exposed to Python through wxPython, so it was extremely powerful and quick. SCONS is a build tool (like make) which knows what to do with swig's .i files.</p> <p>The topmost level can be in C or Python, you'll have more control and fewer packaging and deployment issues if the top level is in C or C++... but it will take a really long time to duplicate what Py2EXE or Py2App gives you on Windows or Mac (or freeze on Linux.) </p> <p>Enjoy the power of hybrid programming! (I call using multiple languages in a tightly coupled way 'hybrid' but it's just a quirk of mine.)</p>
1
2008-11-09T15:33:16Z
[ "java", "c++", "python", "ruby", "perl" ]
Linking languages
271,488
<p>I asked <a href="http://stackoverflow.com/questions/269417/which-language-should-i-use">a question</a> earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. </p> <p>So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better?</p> <p>My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!</p>
15
2008-11-07T08:07:10Z
276,242
<p>If the problem domain is hard (and AI problems can often be hard), then I'd choose a language which is expressive or suited to the domain first, and then worry about speeding it up second. For example, Ruby has meta-programming primitives (ability to easily examine and modify the running program) which can make it very easy/interesting to implement certain types of algorithms.</p> <p>If you implement it in that way and then later need to speed it up, then you can use benchmarking/profiling to locate the bottleneck and either link to a compiled language for that, or optimise the algorithm. In my experience, the biggest performance gain is from tweaking the algorithm, not from using a different implementation language.</p>
1
2008-11-09T18:18:50Z
[ "java", "c++", "python", "ruby", "perl" ]
Interactive console using Pydev in Eclipse?
271,625
<p>I'm debugging my Python code in Eclipse using the Pydev plugin. I'm able to open a Pydev console and it gives me two options: "Console for currently active editor" and "Python console". However none of them is useful to inspect current variable status after a breakpoint.</p> <p>For example, the code stopped at a breakpoint and I want to inspect an "action" variable using the console. However my variables are not available. How can I do things like "dir(action)", etc? (even if it is not using a console).</p>
36
2008-11-07T09:34:27Z
271,692
<p>Double click on "action" or any other variable.</p> <p>ctrl+shift+D</p> <p>And if you're using watches, I cant imagine better interaction. You are able to see every change.</p>
1
2008-11-07T10:16:48Z
[ "python", "debugging", "console", "pydev", "interactive" ]
Interactive console using Pydev in Eclipse?
271,625
<p>I'm debugging my Python code in Eclipse using the Pydev plugin. I'm able to open a Pydev console and it gives me two options: "Console for currently active editor" and "Python console". However none of them is useful to inspect current variable status after a breakpoint.</p> <p>For example, the code stopped at a breakpoint and I want to inspect an "action" variable using the console. However my variables are not available. How can I do things like "dir(action)", etc? (even if it is not using a console).</p>
36
2008-11-07T09:34:27Z
340,875
<p>This feature is documented here:</p> <p><a href="http://pydev.org/manual_adv_debug_console.html">http://pydev.org/manual_adv_debug_console.html</a></p>
29
2008-12-04T15:02:58Z
[ "python", "debugging", "console", "pydev", "interactive" ]
Interactive console using Pydev in Eclipse?
271,625
<p>I'm debugging my Python code in Eclipse using the Pydev plugin. I'm able to open a Pydev console and it gives me two options: "Console for currently active editor" and "Python console". However none of them is useful to inspect current variable status after a breakpoint.</p> <p>For example, the code stopped at a breakpoint and I want to inspect an "action" variable using the console. However my variables are not available. How can I do things like "dir(action)", etc? (even if it is not using a console).</p>
36
2008-11-07T09:34:27Z
1,116,728
<p>When I set a break point and hit F11 Eclipse launches the debugger and prompts to open the "Debug Perspective". You can then open the Window-->Show View --> Expressions which opens the expressions view, you can then right click in the Expressions view windows and choose "Add Watch Expression" to add any expression(such as dir) Conversely I was also able to type in dir(some expression) in the PyDev console and get the same effect. I'm using PyDev 1.4.6.2788</p>
0
2009-07-12T19:38:48Z
[ "python", "debugging", "console", "pydev", "interactive" ]
Interactive console using Pydev in Eclipse?
271,625
<p>I'm debugging my Python code in Eclipse using the Pydev plugin. I'm able to open a Pydev console and it gives me two options: "Console for currently active editor" and "Python console". However none of them is useful to inspect current variable status after a breakpoint.</p> <p>For example, the code stopped at a breakpoint and I want to inspect an "action" variable using the console. However my variables are not available. How can I do things like "dir(action)", etc? (even if it is not using a console).</p>
36
2008-11-07T09:34:27Z
2,117,923
<p>The console that opens in the debug perspective is in fact interactive, although it took me a while to realize it. You need to hit return twice after typing something and then it gets evaluated. More info on the Pydev site here: <a href="http://pydev.org/manual_adv_debug_console.html">http://pydev.org/manual_adv_debug_console.html</a></p>
13
2010-01-22T14:38:10Z
[ "python", "debugging", "console", "pydev", "interactive" ]
Interactive console using Pydev in Eclipse?
271,625
<p>I'm debugging my Python code in Eclipse using the Pydev plugin. I'm able to open a Pydev console and it gives me two options: "Console for currently active editor" and "Python console". However none of them is useful to inspect current variable status after a breakpoint.</p> <p>For example, the code stopped at a breakpoint and I want to inspect an "action" variable using the console. However my variables are not available. How can I do things like "dir(action)", etc? (even if it is not using a console).</p>
36
2008-11-07T09:34:27Z
31,548,800
<p>On a small monitor, you may not realize that the debug interactive console is different from the regular interactive console: it has a second command prompt at the bottom where you type, not at the top like the normal console.</p>
0
2015-07-21T20:16:44Z
[ "python", "debugging", "console", "pydev", "interactive" ]
how to tell if a string is base64 or not
271,657
<p>I have many emails coming in from different sources. they all have attachments, many of them have attachment names in chinese, so these names are converted to base64 by their email clients.</p> <p>When I receive these emails, I wish to decode the name. but there are other names which are not base64. How can I differentiate whether a string is base64 or not, using the <strong>jython</strong> programming language?</p> <p>Ie. </p> <p>First attachment: </p> <pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="Copy of Book1.xls" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="Copy of Book1.xls" </code></pre> <p>second attachment:</p> <pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" </code></pre> <p>Please note both "<strong>Content-Transfer-Encoding</strong>" have base64</p>
6
2008-11-07T09:54:34Z
271,693
<p>Well, you parse the email header into a dictionary. And then you check if Content-Transfer-Encoding is set, and if it = "base64" or "base-64".</p>
0
2008-11-07T10:17:08Z
[ "python", "jython", "base64", "mime" ]
how to tell if a string is base64 or not
271,657
<p>I have many emails coming in from different sources. they all have attachments, many of them have attachment names in chinese, so these names are converted to base64 by their email clients.</p> <p>When I receive these emails, I wish to decode the name. but there are other names which are not base64. How can I differentiate whether a string is base64 or not, using the <strong>jython</strong> programming language?</p> <p>Ie. </p> <p>First attachment: </p> <pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="Copy of Book1.xls" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="Copy of Book1.xls" </code></pre> <p>second attachment:</p> <pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" </code></pre> <p>Please note both "<strong>Content-Transfer-Encoding</strong>" have base64</p>
6
2008-11-07T09:54:34Z
271,705
<p>@gnud, @edg - Unless I misunderstand, he's asking about the filename, not the file content @setori - the Content-Trasfer-Encoding is telling you how the CONTENT of the file is encoded, not the "filename".</p> <p>I'm not an expert, but this part here in the filename is telling him about the characters that follow:</p> <p>=?gb2312?B?</p> <p>I'm looking for the documentation in the RFCs... Ah! here it is: <a href="http://tools.ietf.org/html/rfc2047">http://tools.ietf.org/html/rfc2047</a></p> <p>The RFC says:</p> <p><strong><em>Generally, an "encoded-word" is a sequence of printable ASCII characters that begins with "=?", ends with "?=", and has two "?"s in between.</em></strong> </p> <p>Something else to look at is the code in SharpMimeTools, a MIME parser (in C#) that I use in my <a href="http://ifdefined.com/bugtrackernet.html">bug tracking</a> app, <a href="http://ifdefined.com/bugtrackernet.html">BugTracker.NET</a></p>
7
2008-11-07T10:24:32Z
[ "python", "jython", "base64", "mime" ]
how to tell if a string is base64 or not
271,657
<p>I have many emails coming in from different sources. they all have attachments, many of them have attachment names in chinese, so these names are converted to base64 by their email clients.</p> <p>When I receive these emails, I wish to decode the name. but there are other names which are not base64. How can I differentiate whether a string is base64 or not, using the <strong>jython</strong> programming language?</p> <p>Ie. </p> <p>First attachment: </p> <pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="Copy of Book1.xls" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="Copy of Book1.xls" </code></pre> <p>second attachment:</p> <pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" </code></pre> <p>Please note both "<strong>Content-Transfer-Encoding</strong>" have base64</p>
6
2008-11-07T09:54:34Z
271,720
<p>The header value tells you this:</p> <pre> =?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?= "=?" introduces an encoded value "gb2312" denotes the character encoding of the original value "B" denotes that B-encoding (equal to Base64) was used (the alternative is "Q", which refers to something close to quoted-printable) "?" functions as a separator "uLG..." is the actual value, encoded using the encoding specified before "?=" ends the encoded value </pre> <p>So splitting on "?" actually gets you this (JSON notation)</p> <pre> ["=", "gb2312", "B", "uLGxvmhlbrixsb5nLnhscw==", "="] </pre> <p>In the resulting array, if "B" is on position 2, you face a base-64 encoded string on position 3. Once you decoded it, be sure to pay attention to the encoding on position 1, probably it would be best to convert the whole thing to UTF-8 using that info.</p>
21
2008-11-07T10:35:59Z
[ "python", "jython", "base64", "mime" ]
how to tell if a string is base64 or not
271,657
<p>I have many emails coming in from different sources. they all have attachments, many of them have attachment names in chinese, so these names are converted to base64 by their email clients.</p> <p>When I receive these emails, I wish to decode the name. but there are other names which are not base64. How can I differentiate whether a string is base64 or not, using the <strong>jython</strong> programming language?</p> <p>Ie. </p> <p>First attachment: </p> <pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="Copy of Book1.xls" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="Copy of Book1.xls" </code></pre> <p>second attachment:</p> <pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" </code></pre> <p>Please note both "<strong>Content-Transfer-Encoding</strong>" have base64</p>
6
2008-11-07T09:54:34Z
271,832
<blockquote> <p>Please note both <code>Content-Transfer-Encoding</code> have base64</p> </blockquote> <p>Not relevant in this case, the <code>Content-Transfer-Encoding</code> only applies to the body payload, not to the headers.</p> <pre><code>=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?= </code></pre> <p>That's an <strong>RFC2047</strong>-encoded header atom. The stdlib function to decode it is <code>email.header.decode_header</code>. It still needs a little post-processing to interpret the outcome of that function though:</p> <pre><code>import email.header x= '=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=' try: name= u''.join([ unicode(b, e or 'ascii') for b, e in email.header.decode_header(x) ]) except email.Errors.HeaderParseError: pass # leave name as it was </code></pre> <p>However...</p> <pre><code>Content-Type: application/vnd.ms-excel; name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" </code></pre> <p>This is simply wrong. What mailer created it? RFC2047 encoding can only happen in atoms, and a quoted-string is not an atom. RFC2047 §5 explicitly denies this:</p> <blockquote> <ul> <li>An 'encoded-word' MUST NOT appear within a 'quoted-string'.</li> </ul> </blockquote> <p>The accepted way to encode parameter headers when long string or Unicode characters are present is <strong>RFC2231</strong>, which is a whole new bag of hurt. But you should be using a standard mail-parsing library which will cope with that for you.</p> <p>So, you could detect the <code>'=?'</code> in filename parameters if you want, and try to decode it via RFC2047. However, the strictly-speaking-correct thing to do is to take the mailer at its word and really call the file <code>=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=</code>!</p>
12
2008-11-07T11:38:38Z
[ "python", "jython", "base64", "mime" ]
how to tell if a string is base64 or not
271,657
<p>I have many emails coming in from different sources. they all have attachments, many of them have attachment names in chinese, so these names are converted to base64 by their email clients.</p> <p>When I receive these emails, I wish to decode the name. but there are other names which are not base64. How can I differentiate whether a string is base64 or not, using the <strong>jython</strong> programming language?</p> <p>Ie. </p> <p>First attachment: </p> <pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="Copy of Book1.xls" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="Copy of Book1.xls" </code></pre> <p>second attachment:</p> <pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" </code></pre> <p>Please note both "<strong>Content-Transfer-Encoding</strong>" have base64</p>
6
2008-11-07T09:54:34Z
1,687,765
<p>There is a better way than bobince’s method to handle the output of <code>decode_header</code>. I found it here: <a href="http://mail.python.org/pipermail/email-sig/2007-March/000332.html" rel="nofollow">http://mail.python.org/pipermail/email-sig/2007-March/000332.html</a></p> <pre><code>name = unicode(email.header.make_header(email.header.decode_header(x))) </code></pre>
2
2009-11-06T13:58:52Z
[ "python", "jython", "base64", "mime" ]
how to tell if a string is base64 or not
271,657
<p>I have many emails coming in from different sources. they all have attachments, many of them have attachment names in chinese, so these names are converted to base64 by their email clients.</p> <p>When I receive these emails, I wish to decode the name. but there are other names which are not base64. How can I differentiate whether a string is base64 or not, using the <strong>jython</strong> programming language?</p> <p>Ie. </p> <p>First attachment: </p> <pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="Copy of Book1.xls" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="Copy of Book1.xls" </code></pre> <p>second attachment:</p> <pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" </code></pre> <p>Please note both "<strong>Content-Transfer-Encoding</strong>" have base64</p>
6
2008-11-07T09:54:34Z
2,955,981
<p>Question: """Also I actually need to know what type of file it is ie .xls or .doc so I do need to decode the filename in order to correctly process the attachment, but as above, seems gb2312 is not supported in jython, know any roundabouts?"""</p> <p>Data:</p> <pre><code>Content-Type: application/vnd.ms-excel; name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" </code></pre> <p>Observations:</p> <p>(1) The first line indicates Microsoft Excel, so <code>.xls</code> is looking better than <code>.doc</code></p> <p>(2) </p> <pre><code>&gt;&gt;&gt; import base64 &gt;&gt;&gt; base64.b64decode("uLGxvmhlbrixsb5nLnhscw==") '\xb8\xb1\xb1\xbehen\xb8\xb1\xb1\xbeg.xls' &gt;&gt;&gt; </code></pre> <p>(a) The extension appears to be <code>.xls</code> -- no need for a <code>gb2312</code> codec<br> (b) If you want a file-system-safe file name, you could use the "-_" variant of base64 OR you could percent-encode it<br> (c) For what it's worth, the file name is <code>XYhenXYg.xls</code> where X and Y are 2 Chinese characters that together mean "copy" and the remainder are literal ASCII characters.</p>
0
2010-06-02T08:14:45Z
[ "python", "jython", "base64", "mime" ]
How should I stress test / load test a client server application?
271,825
<p>I develop a client-server style, database based system and I need to devise a way to stress / load test the system. Customers inevitably want to know such things as:</p> <p>• How many clients can a server support?<br /> • How many concurrent searches can a server support?<br /> • How much data can we store in the database?<br /> • Etc.</p> <p>Key to all these questions is response time. We need to be able to measure how response time and performance degrades as new load is introduced so that we could for example, produce some kind of pretty graph we could throw at clients to give them an idea what kind of performance to expect with a given hardware configuration.</p> <p>Right now we just put out fingers in the air and make educated guesses based on what we already know about the system from experience. As the product is put under more demanding conditions, this is proving to be inadequate for our needs going forward though.</p> <p>I've been given the task of devising a method to get such answers in a meaningful way. I realise that this is not a question that anyone can answer definitively but I'm looking for suggestions about how people have gone about doing such work on their own systems.</p> <p>One thing to note is that we have full access to our client API via the Python language (courtesy of SWIG) which is a lot easier to work with than C++ for this kind of work.</p> <p>So there we go, I throw this to the floor: really interested to see what ideas you guys can come up with!</p>
12
2008-11-07T11:35:00Z
271,839
<p><strong>Test 1</strong>: Connect and Disconnect clients like mad, to see how well you handle the init and end of sessions, and just how much your server will survive under spikes, also while doing this measure how many clients fail to connect. That is very important</p> <p><strong>Test 2</strong>: Connect clients and keep them logged on for say a week, doing random actions <a href="http://en.wikipedia.org/wiki/Fuzz_testing">(FuzzTest)</a>. Time the round-trip of each action. Also keep record of the order of actions, because this way your "clients" will find loopholes in your usecases (very important, and VERY hard to test rationally).</p> <p><strong>Test 3 &amp; 4</strong>: Determine major use cases for your system, and write up scripts that do these tasks. Then run several clients doing same task(test 3), and also several clients doing different tasks(test 4).</p> <p><strong>Series:</strong> Now the other dimension you need here is amount of clients. A nice series would be: 5,10,50,100,500,1000,5000,10000,...</p> <p>This way you can get data for each series of tests with different work loads.</p> <p>Also congrats on SWIGing your clients api to Python! That is a great way to get things ready. </p> <p>Note: <a href="http://www.ibm.com/developerworks/java/library/j-fuzztest.html">IBM has a sample of fuzz testing on Java</a>, which is unrealted to your case, but will help you design a good fuzztest for your system</p>
8
2008-11-07T11:44:40Z
[ "python", "database", "client-server", "load-testing", "stress-testing" ]
How should I stress test / load test a client server application?
271,825
<p>I develop a client-server style, database based system and I need to devise a way to stress / load test the system. Customers inevitably want to know such things as:</p> <p>• How many clients can a server support?<br /> • How many concurrent searches can a server support?<br /> • How much data can we store in the database?<br /> • Etc.</p> <p>Key to all these questions is response time. We need to be able to measure how response time and performance degrades as new load is introduced so that we could for example, produce some kind of pretty graph we could throw at clients to give them an idea what kind of performance to expect with a given hardware configuration.</p> <p>Right now we just put out fingers in the air and make educated guesses based on what we already know about the system from experience. As the product is put under more demanding conditions, this is proving to be inadequate for our needs going forward though.</p> <p>I've been given the task of devising a method to get such answers in a meaningful way. I realise that this is not a question that anyone can answer definitively but I'm looking for suggestions about how people have gone about doing such work on their own systems.</p> <p>One thing to note is that we have full access to our client API via the Python language (courtesy of SWIG) which is a lot easier to work with than C++ for this kind of work.</p> <p>So there we go, I throw this to the floor: really interested to see what ideas you guys can come up with!</p>
12
2008-11-07T11:35:00Z
271,853
<p>If you are comfortable coding tests in Python, I've found <a href="http://funkload.nuxeo.org/">funkload</a> to be very capable. You don't say your server is http-based, so you may have to adapt their test facilities to your own client/server style. </p> <p>Once you have a test in Python, funkload can run it on many threads, monitoring response times, and summarizing for you at the end of the test.</p>
6
2008-11-07T11:55:19Z
[ "python", "database", "client-server", "load-testing", "stress-testing" ]
How should I stress test / load test a client server application?
271,825
<p>I develop a client-server style, database based system and I need to devise a way to stress / load test the system. Customers inevitably want to know such things as:</p> <p>• How many clients can a server support?<br /> • How many concurrent searches can a server support?<br /> • How much data can we store in the database?<br /> • Etc.</p> <p>Key to all these questions is response time. We need to be able to measure how response time and performance degrades as new load is introduced so that we could for example, produce some kind of pretty graph we could throw at clients to give them an idea what kind of performance to expect with a given hardware configuration.</p> <p>Right now we just put out fingers in the air and make educated guesses based on what we already know about the system from experience. As the product is put under more demanding conditions, this is proving to be inadequate for our needs going forward though.</p> <p>I've been given the task of devising a method to get such answers in a meaningful way. I realise that this is not a question that anyone can answer definitively but I'm looking for suggestions about how people have gone about doing such work on their own systems.</p> <p>One thing to note is that we have full access to our client API via the Python language (courtesy of SWIG) which is a lot easier to work with than C++ for this kind of work.</p> <p>So there we go, I throw this to the floor: really interested to see what ideas you guys can come up with!</p>
12
2008-11-07T11:35:00Z
271,891
<p>If you have the budget, LoadRunner would be perfect for this.</p>
0
2008-11-07T12:16:08Z
[ "python", "database", "client-server", "load-testing", "stress-testing" ]
How should I stress test / load test a client server application?
271,825
<p>I develop a client-server style, database based system and I need to devise a way to stress / load test the system. Customers inevitably want to know such things as:</p> <p>• How many clients can a server support?<br /> • How many concurrent searches can a server support?<br /> • How much data can we store in the database?<br /> • Etc.</p> <p>Key to all these questions is response time. We need to be able to measure how response time and performance degrades as new load is introduced so that we could for example, produce some kind of pretty graph we could throw at clients to give them an idea what kind of performance to expect with a given hardware configuration.</p> <p>Right now we just put out fingers in the air and make educated guesses based on what we already know about the system from experience. As the product is put under more demanding conditions, this is proving to be inadequate for our needs going forward though.</p> <p>I've been given the task of devising a method to get such answers in a meaningful way. I realise that this is not a question that anyone can answer definitively but I'm looking for suggestions about how people have gone about doing such work on their own systems.</p> <p>One thing to note is that we have full access to our client API via the Python language (courtesy of SWIG) which is a lot easier to work with than C++ for this kind of work.</p> <p>So there we go, I throw this to the floor: really interested to see what ideas you guys can come up with!</p>
12
2008-11-07T11:35:00Z
271,918
<p>For performance you are looking at two things: latency (the responsiveness of the application) and throughput (how many ops per interval). For latency you need to have an acceptable benchmark. For throughput you need to have a minimum acceptable throughput.</p> <p>These are you starting points. For telling a client how many xyz's you can do per interval then you are going to need to know the hardware and software configuration. Knowing the production hardware is important to getting accurate figures. If you do not know the hardware configuration then you need to devise a way to map your figures from the test hardware to the eventual production hardware.</p> <p>Without knowledge of hardware then you can really only observe trends in performance over time rather than absolutes.</p> <p>Knowing the software configuration is equally important. Do you have a clustered server configuration, is it load balanced, is there anything else running on the server? Can you scale your software or do you have to scale the hardware to meet demand.</p> <p>To know how many clients you can support you need to understand what is a standard set of operations. A quick test is to remove the client and write a stub client and the spin up as many of these as you can. Have each one connect to the server. You will eventually reach the server connection resource limit. Without connection pooling or better hardware you can't get higher than this. Often you will hit a architectural issue before here but in either case you have an upper bounds.</p> <p>Take this information and design a script that your client can enact. You need to map how long your script takes to perform the action with respect to how long it will take the expected user to do it. Start increasing your numbers as mentioned above to you hit the point where the increase in clients causes a greater decrease in performance. </p> <p>There are many ways to stress test but the key is understanding expected load. Ask your client about their expectations. What is the expected demand per interval? From there you can work out upper loads.</p> <p>You can do a soak test with many clients operating continously for many hours or days. You can try to connect as many clients as you can as fast you can to see how well your server handles high demand (also a DOS attack). </p> <p>Concurrent searches should be done through your standard behaviour searches acting on behalf of the client or, write a script to establish a semaphore that waits on many threads, then you can release them all at once. This is fun and punishes your database. When performing searches you need to take into account any caching layers that may exist. You need to test both caching and without caching (in scenarios where everyone makes unique search requests).</p> <p>Database storage is based on physical space; you can determine row size from the field lengths and expected data population. Extrapolate this out statistically or create a data generation script (useful for your load testing scenarios and should be an asset to your organisation) and then map the generated data to business objects. Your clients will care about how many "business objects" they can store while you will care about how much raw data can be stored.</p> <p>Other things to consider: What is the expected availability? What about how long it takes to bring a server online. 99.9% availability is not good if it takes two days to bring back online the one time it does go down. On the flip side a lower availablility is more acceptable if it takes 5 seconds to reboot and you have a fall over.</p>
5
2008-11-07T12:25:41Z
[ "python", "database", "client-server", "load-testing", "stress-testing" ]
How should I stress test / load test a client server application?
271,825
<p>I develop a client-server style, database based system and I need to devise a way to stress / load test the system. Customers inevitably want to know such things as:</p> <p>• How many clients can a server support?<br /> • How many concurrent searches can a server support?<br /> • How much data can we store in the database?<br /> • Etc.</p> <p>Key to all these questions is response time. We need to be able to measure how response time and performance degrades as new load is introduced so that we could for example, produce some kind of pretty graph we could throw at clients to give them an idea what kind of performance to expect with a given hardware configuration.</p> <p>Right now we just put out fingers in the air and make educated guesses based on what we already know about the system from experience. As the product is put under more demanding conditions, this is proving to be inadequate for our needs going forward though.</p> <p>I've been given the task of devising a method to get such answers in a meaningful way. I realise that this is not a question that anyone can answer definitively but I'm looking for suggestions about how people have gone about doing such work on their own systems.</p> <p>One thing to note is that we have full access to our client API via the Python language (courtesy of SWIG) which is a lot easier to work with than C++ for this kind of work.</p> <p>So there we go, I throw this to the floor: really interested to see what ideas you guys can come up with!</p>
12
2008-11-07T11:35:00Z
11,406,913
<p>On a related note: Twitter recently OpenSourced their <a href="https://github.com/twitter/iago/" rel="nofollow">load-testing framework</a>. Could be worth a go :)</p>
0
2012-07-10T05:04:21Z
[ "python", "database", "client-server", "load-testing", "stress-testing" ]
How to scan a webpage and get images and youtube embeds?
271,855
<p>I am building a web app where I need to get all the images and any flash videos that are embedded (e.g. youtube) on a given URL. I'm using Python.</p> <p>I've googled, but have not found any good information about this (probably because I don't know what this is called to search for), does anyone have any experience with this and knows how it can be done?</p> <p>I'd love to see some code examples if there are any available. </p> <p>Thanks!</p>
2
2008-11-07T11:55:41Z
271,860
<p><a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> is a great screen-scraping library. Use urllib2 to fetch the page, and BeautifulSoup to parse it apart. Here's a code sample from their docs:</p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup page = urllib2.urlopen("http://www.icc-ccs.org/prc/piracyreport.php") soup = BeautifulSoup(page) for incident in soup('td', width="90%"): where, linebreak, what = incident.contents[:3] print where.strip() print what.strip() print </code></pre>
7
2008-11-07T11:58:27Z
[ "python", "web-applications", "screen-scraping" ]
User Authentication in Django
272,042
<p>is there any way of making sure that, one user is logged in only once?</p> <p>I would like to avoid two different persons logging into the system with the same login/password.</p> <p>I guess I could do it myself by checking in the django_session table before logging in the user, but I rather prefer using the framework, if there is already such functionality.</p> <p>Cheers,</p> <p>Thanks for the responses!</p>
2
2008-11-07T13:21:04Z
272,071
<p>Logged in twice is ambiguous over HTTP. There's no "disconnecting" signal that's sent. You can frustrate people if you're not careful.</p> <p>If I shut down my browser and drop the cookies -- accidentally -- I might be prevented from logging in again. </p> <p>How would the server know it was me trying to re-login vs. me trying to login twice? </p> <p>You can try things like checking the IP address. And what if the accidental disconnect was my router crashing, releasing my DHCP lease? Now I'm trying to re-login, but I have a new address and no established cookie. I'm not trying to create a second session, I'm just trying to get back on after my current session got disconnected.</p> <p>the point is that there's no well-established rule for "single session" that can be installed in a framework. You have to make up a rule appropriate to your application and figure out how to enforce it.</p>
5
2008-11-07T13:37:07Z
[ "python", "django" ]
User Authentication in Django
272,042
<p>is there any way of making sure that, one user is logged in only once?</p> <p>I would like to avoid two different persons logging into the system with the same login/password.</p> <p>I guess I could do it myself by checking in the django_session table before logging in the user, but I rather prefer using the framework, if there is already such functionality.</p> <p>Cheers,</p> <p>Thanks for the responses!</p>
2
2008-11-07T13:21:04Z
272,470
<p>A site I did last year was concerned that usernames/passwords might be posted to a forum. I dealt with this by adding a model and a check to the login view that looked at how many unique IPs the name had been used from in the last X hours. I gave the site admins two values in settings.py to adjust the number of hours and the number of unique IPs. If a name was being "overused" it was blocked for logins from new IPs until enough time had passed to fall below the threshold.</p> <p>Much to their surprise, they have had only one name trigger the blocking in the last year and that turned out to be the company president who was on a business trip and kept logging in from new locations.</p> <p>Ps. The code is straightforward. Email me at peter at techbuddy dot us if you would like it.</p>
4
2008-11-07T15:39:19Z
[ "python", "django" ]
Code Coverage and Unit Testing of Python Code
272,188
<p>I have already visited <a href="http://stackoverflow.com/questions/191673/preferred-python-unit-testing-framework">Preferred Python unit-testing framework</a>. I am not just looking at Python Unit Testing Framework, but also code coverage with respect to unit tests. So far I have only come across <a href="http://nedbatchelder.com/code/modules/coverage.html">coverage.py</a>. Is there any better option?</p> <p>An interesting option for me is to integrate <a href="http://www.python.org/">cpython</a>, unit testing of Python code and code coverage of Python code with Visual Studio 2008 through plugins (something similar to <a href="http://www.codeplex.com/IronPythonStudio">IronPython Studio</a>). What can be done to achieve this? I look forward to suggestions.</p>
25
2008-11-07T14:19:49Z
272,605
<p>There is also <a href="http://darcs.idyll.org/~t/projects/figleaf/doc/" rel="nofollow">figleaf</a> which I think is based on Ned Batchelder's coverage.py. We use <a href="http://somethingaboutorange.com/mrl/projects/nose/" rel="nofollow">nose</a> as the driver for the testing. It all works pretty well. We write our unit tests using the built-in unittest and doctest modules.</p>
2
2008-11-07T16:22:17Z
[ "python", "visual-studio-2008", "unit-testing", "code-coverage" ]
Code Coverage and Unit Testing of Python Code
272,188
<p>I have already visited <a href="http://stackoverflow.com/questions/191673/preferred-python-unit-testing-framework">Preferred Python unit-testing framework</a>. I am not just looking at Python Unit Testing Framework, but also code coverage with respect to unit tests. So far I have only come across <a href="http://nedbatchelder.com/code/modules/coverage.html">coverage.py</a>. Is there any better option?</p> <p>An interesting option for me is to integrate <a href="http://www.python.org/">cpython</a>, unit testing of Python code and code coverage of Python code with Visual Studio 2008 through plugins (something similar to <a href="http://www.codeplex.com/IronPythonStudio">IronPython Studio</a>). What can be done to achieve this? I look forward to suggestions.</p>
25
2008-11-07T14:19:49Z
273,246
<p>We use this <a href="http://www.djangosnippets.org/snippets/705/" rel="nofollow">Django coverage integration</a>, but instead of using the default coverage.py reporting, we generate some simple HTML: <a href="http://code.activestate.com/recipes/52298/" rel="nofollow">Colorize Python source using the built-in tokenizer</a>.</p>
5
2008-11-07T19:10:05Z
[ "python", "visual-studio-2008", "unit-testing", "code-coverage" ]
Code Coverage and Unit Testing of Python Code
272,188
<p>I have already visited <a href="http://stackoverflow.com/questions/191673/preferred-python-unit-testing-framework">Preferred Python unit-testing framework</a>. I am not just looking at Python Unit Testing Framework, but also code coverage with respect to unit tests. So far I have only come across <a href="http://nedbatchelder.com/code/modules/coverage.html">coverage.py</a>. Is there any better option?</p> <p>An interesting option for me is to integrate <a href="http://www.python.org/">cpython</a>, unit testing of Python code and code coverage of Python code with Visual Studio 2008 through plugins (something similar to <a href="http://www.codeplex.com/IronPythonStudio">IronPython Studio</a>). What can be done to achieve this? I look forward to suggestions.</p>
25
2008-11-07T14:19:49Z
288,711
<p><a href="http://code.google.com/p/testoob/" rel="nofollow">Testoob</a> has a neat "<code>--coverage</code>" command-line option to generate a coverage report.</p>
0
2008-11-13T23:12:22Z
[ "python", "visual-studio-2008", "unit-testing", "code-coverage" ]
Code Coverage and Unit Testing of Python Code
272,188
<p>I have already visited <a href="http://stackoverflow.com/questions/191673/preferred-python-unit-testing-framework">Preferred Python unit-testing framework</a>. I am not just looking at Python Unit Testing Framework, but also code coverage with respect to unit tests. So far I have only come across <a href="http://nedbatchelder.com/code/modules/coverage.html">coverage.py</a>. Is there any better option?</p> <p>An interesting option for me is to integrate <a href="http://www.python.org/">cpython</a>, unit testing of Python code and code coverage of Python code with Visual Studio 2008 through plugins (something similar to <a href="http://www.codeplex.com/IronPythonStudio">IronPython Studio</a>). What can be done to achieve this? I look forward to suggestions.</p>
25
2008-11-07T14:19:49Z
324,468
<p>PyDev seems to allow code coverage from within Eclipse. </p> <p>I've yet to find how to integrate that with my own (rather complex) build process, so I use Ned Batchelder's coverage.py at the command line.</p>
4
2008-11-27T18:50:18Z
[ "python", "visual-studio-2008", "unit-testing", "code-coverage" ]
Code Coverage and Unit Testing of Python Code
272,188
<p>I have already visited <a href="http://stackoverflow.com/questions/191673/preferred-python-unit-testing-framework">Preferred Python unit-testing framework</a>. I am not just looking at Python Unit Testing Framework, but also code coverage with respect to unit tests. So far I have only come across <a href="http://nedbatchelder.com/code/modules/coverage.html">coverage.py</a>. Is there any better option?</p> <p>An interesting option for me is to integrate <a href="http://www.python.org/">cpython</a>, unit testing of Python code and code coverage of Python code with Visual Studio 2008 through plugins (something similar to <a href="http://www.codeplex.com/IronPythonStudio">IronPython Studio</a>). What can be done to achieve this? I look forward to suggestions.</p>
25
2008-11-07T14:19:49Z
373,619
<p>NetBeans' new Python support has tightly integrated code coverage support - <a href="http://blogs.oracle.com/tor/entry/netbeans_screenshot_of_the_week6" rel="nofollow">more info here</a>.</p>
2
2008-12-17T03:58:49Z
[ "python", "visual-studio-2008", "unit-testing", "code-coverage" ]
Code Coverage and Unit Testing of Python Code
272,188
<p>I have already visited <a href="http://stackoverflow.com/questions/191673/preferred-python-unit-testing-framework">Preferred Python unit-testing framework</a>. I am not just looking at Python Unit Testing Framework, but also code coverage with respect to unit tests. So far I have only come across <a href="http://nedbatchelder.com/code/modules/coverage.html">coverage.py</a>. Is there any better option?</p> <p>An interesting option for me is to integrate <a href="http://www.python.org/">cpython</a>, unit testing of Python code and code coverage of Python code with Visual Studio 2008 through plugins (something similar to <a href="http://www.codeplex.com/IronPythonStudio">IronPython Studio</a>). What can be done to achieve this? I look forward to suggestions.</p>
25
2008-11-07T14:19:49Z
2,705,889
<p>If you want interactive code coverage, where you can see your coverage stats change in real time, take a look at <a href="http://www.softwareverify.com/python/coverage/index.html" rel="nofollow">Python Coverage Validator</a>.</p>
1
2010-04-24T19:46:26Z
[ "python", "visual-studio-2008", "unit-testing", "code-coverage" ]
"File -X: does not exist" message from ipy.exe in Windows PowerShell
272,233
<p>If I type this line in an MS-DOS command prompt window: </p> <pre><code>ipy -X:ColorfulConsole </code></pre> <p>IronPython starts up as expected with the colorful console option enabled. However, if I type the same line in Windows PowerShell I get the message: </p> <pre><code>File -X: does not exist </code></pre> <p>Can someone explain what I'm doing wrong?</p>
1
2008-11-07T14:31:30Z
272,283
<p>try:</p> <pre><code>ipy '-X:ColorfulConsole' </code></pre> <p>Or whatever quoting mechanism is supported in Windows PowerShell - the shell is splitting your argument. </p> <p>Typing</p> <pre><code>ipy -X: ColorfulConsole </code></pre> <p>in MS-DOS command prompt window returns same response <code>File -X: does not exist</code>.</p>
5
2008-11-07T14:45:15Z
[ "python", "powershell", "ironpython" ]
Python's os.execvp equivalent for PHP
272,826
<p>I've got a PHP command line program running. And I want to connect to a mysql shell straight from PHP. I've done this before in Python using os.execvp But I can't get the same thing to work in PHP.</p> <p>I've tried the following functions:</p> <ul> <li>system</li> <li>passthru</li> <li>exec</li> <li>shell_exec</li> </ul> <p>example:</p> <pre><code>system('mysql -u root -pxxxx db_name'); </code></pre> <p>But they all seem to wait for mysql to exit and return something. What I really want is for PHP to launch the mysql shell and then exit it self. any ideas?</p>
4
2008-11-07T17:21:55Z
272,845
<p>Give MySQL a script to run that's separate from the PHP script:</p> <pre><code>system('mysql -u root -pxxxx db_name &lt; script.mysql'); </code></pre>
0
2008-11-07T17:26:48Z
[ "php", "python", "shell", "command-line-interface" ]
Python's os.execvp equivalent for PHP
272,826
<p>I've got a PHP command line program running. And I want to connect to a mysql shell straight from PHP. I've done this before in Python using os.execvp But I can't get the same thing to work in PHP.</p> <p>I've tried the following functions:</p> <ul> <li>system</li> <li>passthru</li> <li>exec</li> <li>shell_exec</li> </ul> <p>example:</p> <pre><code>system('mysql -u root -pxxxx db_name'); </code></pre> <p>But they all seem to wait for mysql to exit and return something. What I really want is for PHP to launch the mysql shell and then exit it self. any ideas?</p>
4
2008-11-07T17:21:55Z
272,894
<p>In addition to what acrosman said, you can also use the <code>-e</code> switch to pass SQL from the command line.</p> <pre><code>$sql = "....."; system("mysql -u root -pxxxx db_name -e \"$sql\""); </code></pre> <p>Also, I hope your not actually connecting to the database as root from a PHP application.</p>
0
2008-11-07T17:37:35Z
[ "php", "python", "shell", "command-line-interface" ]
Python's os.execvp equivalent for PHP
272,826
<p>I've got a PHP command line program running. And I want to connect to a mysql shell straight from PHP. I've done this before in Python using os.execvp But I can't get the same thing to work in PHP.</p> <p>I've tried the following functions:</p> <ul> <li>system</li> <li>passthru</li> <li>exec</li> <li>shell_exec</li> </ul> <p>example:</p> <pre><code>system('mysql -u root -pxxxx db_name'); </code></pre> <p>But they all seem to wait for mysql to exit and return something. What I really want is for PHP to launch the mysql shell and then exit it self. any ideas?</p>
4
2008-11-07T17:21:55Z
273,992
<p>If you want shell commands to be interactive, use:</p> <pre><code>system("mysql -uroot -p db_name &gt; `tty`"); </code></pre> <p>That will work for most cases, but will break if you aren't in a terminal.</p>
3
2008-11-07T23:28:59Z
[ "php", "python", "shell", "command-line-interface" ]
Generating a WSDL using Python and SOAPpy
273,002
<p>First of all, I will admit I am a novice to web services, although I'm familiar with HTML and basic web stuff. I created a quick-and-dirty web service using Python that calls a stored procedure in a MySQL database, that simply returns a BIGINT value. I want to return this value in the web service, and I want to generate a WSDL that I can give our web developers. I might add that the stored procedure only returns one value.</p> <p>Here's some example code:</p> <pre><code>#!/usr/bin/python import SOAPpy import MySQLdb def getNEXTVAL(): cursor = db.cursor() cursor.execute( "CALL my_stored_procedure()" ) # Returns a number result=cursor.fetchall() for record in result: return record[0] db=MySQLdb.connect(host="localhost", user="myuser", passwd="********", db="testing") server = SOAPpy.SOAPServer(("10.1.22.29", 8080)) server.registerFunction(getNEXTVAL) server.serve_forever() </code></pre> <p>I want to generate a WSDL that I can give to the web folks, and I'm wondering if it's possible to have SOAPpy just generate one for me. Is this possible?</p>
11
2008-11-07T18:05:08Z
274,366
<blockquote> <p>I want to generate a WSDL that I can give to the web folks, ....</p> </blockquote> <p>You can try <a href="http://soaplib.github.com/soaplib/2_0/" rel="nofollow">soaplib</a>. It has on-demand WSDL generation.</p>
1
2008-11-08T04:34:26Z
[ "python", "soap", "wsdl", "soappy", "zsi" ]
Generating a WSDL using Python and SOAPpy
273,002
<p>First of all, I will admit I am a novice to web services, although I'm familiar with HTML and basic web stuff. I created a quick-and-dirty web service using Python that calls a stored procedure in a MySQL database, that simply returns a BIGINT value. I want to return this value in the web service, and I want to generate a WSDL that I can give our web developers. I might add that the stored procedure only returns one value.</p> <p>Here's some example code:</p> <pre><code>#!/usr/bin/python import SOAPpy import MySQLdb def getNEXTVAL(): cursor = db.cursor() cursor.execute( "CALL my_stored_procedure()" ) # Returns a number result=cursor.fetchall() for record in result: return record[0] db=MySQLdb.connect(host="localhost", user="myuser", passwd="********", db="testing") server = SOAPpy.SOAPServer(("10.1.22.29", 8080)) server.registerFunction(getNEXTVAL) server.serve_forever() </code></pre> <p>I want to generate a WSDL that I can give to the web folks, and I'm wondering if it's possible to have SOAPpy just generate one for me. Is this possible?</p>
11
2008-11-07T18:05:08Z
276,994
<p>When I tried to write Python web service last year, I ended up using <a href="http://pywebsvcs.sourceforge.net/">ZSI-2.0</a> (which is something like heir of SOAPpy) and a <a href="http://pywebsvcs.sourceforge.net/holger.pdf">paper available on its web</a>.</p> <p>Basically I wrote my WSDL file by hand and then used ZSI stuff to generate stubs for my client and server code. I wouldn't describe the experience as pleasant, but the application did work.</p>
8
2008-11-10T03:25:11Z
[ "python", "soap", "wsdl", "soappy", "zsi" ]
Generating a WSDL using Python and SOAPpy
273,002
<p>First of all, I will admit I am a novice to web services, although I'm familiar with HTML and basic web stuff. I created a quick-and-dirty web service using Python that calls a stored procedure in a MySQL database, that simply returns a BIGINT value. I want to return this value in the web service, and I want to generate a WSDL that I can give our web developers. I might add that the stored procedure only returns one value.</p> <p>Here's some example code:</p> <pre><code>#!/usr/bin/python import SOAPpy import MySQLdb def getNEXTVAL(): cursor = db.cursor() cursor.execute( "CALL my_stored_procedure()" ) # Returns a number result=cursor.fetchall() for record in result: return record[0] db=MySQLdb.connect(host="localhost", user="myuser", passwd="********", db="testing") server = SOAPpy.SOAPServer(("10.1.22.29", 8080)) server.registerFunction(getNEXTVAL) server.serve_forever() </code></pre> <p>I want to generate a WSDL that I can give to the web folks, and I'm wondering if it's possible to have SOAPpy just generate one for me. Is this possible?</p>
11
2008-11-07T18:05:08Z
8,336,051
<p>Sorry for the question few days ago. Now I can invoke the server successfully. A demo is provided:</p> <pre><code>def test_soappy(): """test for SOAPpy.SOAPServer """ #okay # it's good for SOAPpy.SOAPServer. # in a method,it can have morn than 2 ws server. server = SOAPProxy("http://localhost:8081/") print server.sum(1,2) print server.div(10,2) </code></pre>
0
2011-12-01T02:59:53Z
[ "python", "soap", "wsdl", "soappy", "zsi" ]
Python memory debugging with GDB
273,043
<p>We have a Linux application that makes use of OpenSSL's Python bindings and I suspect it is causing random crashes. Occasionally, we see it crash with the message "Python Fatal Error: GC Object already tracked," which would appear to be either a programming error on the part of the library, or a symptom of memory corruption. Is there any way to know the last line of Python source code it executed, given a core file? Or if it is attached in GDB? I realize it is probably all compiled bytecode, but I'm hoping there someone out there may have dealt with this. Currently it is running with the trace module active and we're hoping it will happen again, but it could be a long while.</p>
4
2008-11-07T18:13:58Z
273,063
<p>If you have mac or sun box kicking around you could use <a href="http://en.wikipedia.org/wiki/DTrace" rel="nofollow">dtrace</a> and a version of python compiled with dtrace to figure out what the application was doing at the time. Note: in 10.5 python is pre-compiled with dtrace which is really nice and handy.</p> <p>If that isn't available to you, then you can <a href="http://www.python.org/doc/2.5.2/lib/module-gc.html" rel="nofollow">import gc</a> and enable debugging which you can then put out to a log file.</p> <p>To specifically answer your question regarding debugging with GDB you might want to read "<a href="http://wiki.python.org/moin/DebuggingWithGdb" rel="nofollow">Debugging With GDB</a>" on the python wiki.</p>
1
2008-11-07T18:20:16Z
[ "python", "linux", "debugging", "openssl" ]
Python memory debugging with GDB
273,043
<p>We have a Linux application that makes use of OpenSSL's Python bindings and I suspect it is causing random crashes. Occasionally, we see it crash with the message "Python Fatal Error: GC Object already tracked," which would appear to be either a programming error on the part of the library, or a symptom of memory corruption. Is there any way to know the last line of Python source code it executed, given a core file? Or if it is attached in GDB? I realize it is probably all compiled bytecode, but I'm hoping there someone out there may have dealt with this. Currently it is running with the trace module active and we're hoping it will happen again, but it could be a long while.</p>
4
2008-11-07T18:13:58Z
273,111
<p>Yes, you can do this kind of thing:</p> <pre><code>(gdb) print PyRun_SimpleString("import traceback; traceback.print_stack()") File "&lt;string&gt;", line 1, in &lt;module&gt; File "/var/tmp/foo.py", line 2, in &lt;module&gt; i**2 File "&lt;string&gt;", line 1, in &lt;module&gt; $1 = 0 </code></pre> <p>It should also be possible to use the <code>pystack</code> command defined in the python <a href="http://svn.python.org/view/python/trunk/Misc/gdbinit?view=auto">gdbinit</a> file, but it's not working for me. It's discussed <a href="http://wiki.python.org/moin/DebuggingWithGdb">here</a> if you want to look into it.</p> <p>Also, if you suspect memory issues, it's worth noting that you can use <a href="http://valgrind.org/"><code>valgrind</code></a> with python, if you're prepared to recompile it. The procedure is described <a href="http://svn.python.org/projects/python/trunk/Misc/README.valgrind">here.</a></p>
5
2008-11-07T18:36:04Z
[ "python", "linux", "debugging", "openssl" ]
Python memory debugging with GDB
273,043
<p>We have a Linux application that makes use of OpenSSL's Python bindings and I suspect it is causing random crashes. Occasionally, we see it crash with the message "Python Fatal Error: GC Object already tracked," which would appear to be either a programming error on the part of the library, or a symptom of memory corruption. Is there any way to know the last line of Python source code it executed, given a core file? Or if it is attached in GDB? I realize it is probably all compiled bytecode, but I'm hoping there someone out there may have dealt with this. Currently it is running with the trace module active and we're hoping it will happen again, but it could be a long while.</p>
4
2008-11-07T18:13:58Z
273,204
<p>If you're using CDLL to wrap a C library in python, and this is 64-bit linux, there's a good chance that you're CDLL wrapper is misconfigured. CDLL defaults to int return types on all platforms (should be a long long on 64-bit systems) and just expects you to pass the right arguments in. You may need to verify the CDLL wrapper in this case...</p>
0
2008-11-07T18:59:10Z
[ "python", "linux", "debugging", "openssl" ]
Python memory debugging with GDB
273,043
<p>We have a Linux application that makes use of OpenSSL's Python bindings and I suspect it is causing random crashes. Occasionally, we see it crash with the message "Python Fatal Error: GC Object already tracked," which would appear to be either a programming error on the part of the library, or a symptom of memory corruption. Is there any way to know the last line of Python source code it executed, given a core file? Or if it is attached in GDB? I realize it is probably all compiled bytecode, but I'm hoping there someone out there may have dealt with this. Currently it is running with the trace module active and we're hoping it will happen again, but it could be a long while.</p>
4
2008-11-07T18:13:58Z
273,212
<p>In addition to all above one can quickly implement an adhoc tracer via the <a href="http://www.python.org/doc/2.5.2/lib/module-trace.html" rel="nofollow">trace module</a>.</p>
0
2008-11-07T19:03:15Z
[ "python", "linux", "debugging", "openssl" ]
Testing Web Services Consumer
273,060
<p>Here are some tools that I have found to test web services consumers:</p> <p><a href="http://www.soapui.org/" rel="nofollow">http://www.soapui.org/</a> https://wsunit.dev.java.net/</p> <p>Are there any others? I would prefer testing frameworks that are written in Java or Python.</p>
2
2008-11-07T18:19:54Z
273,116
<p>The Grinder is right up your ally with both Java and Python, that handles most web services, (SOAP/REST/CORBA/RMI/JMS/EJB) etc.</p> <p><a href="http://grinder.sourceforge.net/" rel="nofollow">http://grinder.sourceforge.net/</a></p>
0
2008-11-07T18:36:57Z
[ "java", "python", "web-services", "testing", "integration-testing" ]
Testing Web Services Consumer
273,060
<p>Here are some tools that I have found to test web services consumers:</p> <p><a href="http://www.soapui.org/" rel="nofollow">http://www.soapui.org/</a> https://wsunit.dev.java.net/</p> <p>Are there any others? I would prefer testing frameworks that are written in Java or Python.</p>
2
2008-11-07T18:19:54Z
273,681
<p>I have used soapui by a maven plugin. It can create junit-linke reports to be run and analysed like unit tests. This can be easily integrated in continious build, also with the free distribution of soapui.</p>
1
2008-11-07T21:23:27Z
[ "java", "python", "web-services", "testing", "integration-testing" ]
Testing Web Services Consumer
273,060
<p>Here are some tools that I have found to test web services consumers:</p> <p><a href="http://www.soapui.org/" rel="nofollow">http://www.soapui.org/</a> https://wsunit.dev.java.net/</p> <p>Are there any others? I would prefer testing frameworks that are written in Java or Python.</p>
2
2008-11-07T18:19:54Z
276,338
<p>I've used <a href="http://www.codeplex.com/WebserviceStudio" rel="nofollow">Web Service Studio</a>.</p> <blockquote> <p><strong>Web Service Studio</strong> is a tool to invoke web methods interactively. The user can provide a WSDL endpoint. On clicking button Get the tool fetches the WSDL, generates .NET proxy from the WSDL and displays the list of methods available. The user can choose any method and provide the required input parameters. On clicking Invoke the SOAP request is sent to the server and the response is parsed to display the return value.</p> <p>This tool is meant for web service implementers to test their web services without having to write the client code. This could also be used to access other web services whose WSDL endpoint is known.</p> </blockquote> <p>Also the <strong>Web Services Explorer</strong> in Eclipse which comes as part of the <a href="http://www.eclipse.org/webtools/" rel="nofollow">Web Tools Platform</a>.</p> <blockquote> <p>Through UDDI and WSIL, other applications can discover WSDL documents and bind with them to execute transactions or perform other business processes. The Web Services Explorer allows you to explore, import, and test WSDL documents.</p> </blockquote>
1
2008-11-09T19:20:43Z
[ "java", "python", "web-services", "testing", "integration-testing" ]
Testing Web Services Consumer
273,060
<p>Here are some tools that I have found to test web services consumers:</p> <p><a href="http://www.soapui.org/" rel="nofollow">http://www.soapui.org/</a> https://wsunit.dev.java.net/</p> <p>Are there any others? I would prefer testing frameworks that are written in Java or Python.</p>
2
2008-11-07T18:19:54Z
284,528
<p>You really need to be more specific: What is it that you want to test in your WS-consumer? That it calls the right WS? This looks a bit pointless - WS are a perfect place for mocking whatever may be called - without anything being called.</p> <p>In order to test the consumer you'd otherwise be writing a Webservice that mocks the original, right? I'd suppose that the communication protocol that goes through the wire is not the clients domain - e.g. it's generated. So the only thing a WS-consumer's client sees is the interface. And there's nothing to test in an interface.</p> <p>It might be that I completely misunderstood your question - please clarify if I did. I'll revise the answer then.</p>
0
2008-11-12T16:36:36Z
[ "java", "python", "web-services", "testing", "integration-testing" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
273,206
<p>Try the <a href="https://docs.python.org/2/library/os.path.html#os.path.exists"><code>os.path.exists</code></a> function</p> <pre><code>if not os.path.exists(dir): os.mkdir(dir) </code></pre>
10
2008-11-07T19:00:01Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
273,208
<p>Check out <a href="https://docs.python.org/3/library/os.html#os.makedirs">os.makedirs</a>: (It makes sure the complete path exists.) To handle the fact the directory might exist, catch OSError.</p> <pre><code>import os try: os.makedirs('./path/to/somewhere') except OSError: pass </code></pre>
40
2008-11-07T19:01:25Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
273,227
<p>I see two answers with good qualities, each with a small flaw, so I will give my take on it:</p> <p>Try <a href="https://docs.python.org/2/library/os.path.html#os.path.exists"><code>os.path.exists</code></a>, and consider <a href="https://docs.python.org/2/library/os.html#os.makedirs"><code>os.makedirs</code></a> for the creation.</p> <pre><code>if not os.path.exists(directory): os.makedirs(directory) </code></pre> <p>As noted in comments and elsewhere, there's a race condition - if the directory is created between the <code>os.path.exists</code> and the <code>os.makedirs</code> calls, the <code>os.makedirs</code> will fail with an <code>OSError</code>. Unfortunately, blanket-catching <code>OSError</code> and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.</p> <p>One option would be to trap the <code>OSError</code> and examine the embedded error code, if one knew what's what (on my OS, 13 seems to indicate that permission is denied, and 17 that the file exists - it's not clear that that's even remotely portable, but is explored in <a href="http://stackoverflow.com/questions/273698/is-there-a-cross-platform-way-of-getting-information-from-pythons-oserror">Is there a cross-platform way of getting information from Python’s OSError</a>). Alternatively, there could be a second <code>os.path.exists</code>, but suppose another created the directory after the first check, then removed it before the second one - we could still be fooled. </p> <p>Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.</p>
2,049
2008-11-07T19:06:07Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
273,679
<p>I have put the following down. It's not totally foolproof though.</p> <pre><code>import os dirname = 'create/me' try: os.makedirs(dirname) except OSError: if os.path.exists(dirname): # We are nearly safe pass else: # There was an error on creation, so make sure we know about it raise </code></pre> <p>Now as I say, this is not really foolproof, because we have the possiblity of failing to create the directory, and another process creating it during that period.</p>
17
2008-11-07T21:23:03Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
444,023
<p>I would personally recommend that you use <code>os.path.isdir()</code> to test instead of <code>os.path.exists()</code>.</p> <pre><code>&gt;&gt;&gt; os.path.exists('/tmp/dirname') True &gt;&gt;&gt; os.path.exists('/tmp/dirname/filename.etc') True &gt;&gt;&gt; os.path.isdir('/tmp/dirname/filename.etc') False &gt;&gt;&gt; os.path.isdir('/tmp/fakedirname') False </code></pre> <p>If you have:</p> <pre><code>&gt;&gt;&gt; dir = raw_input(":: ") </code></pre> <p>And a foolish user input:</p> <pre><code>:: /tmp/dirname/filename.etc </code></pre> <p>... You're going to end up with a directory named <code>filename.etc</code> when you pass that argument to <code>os.makedirs()</code> if you test with <code>os.path.exists()</code>.</p>
63
2009-01-14T17:57:32Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
5,032,238
<p>Using try except and the right error code from errno module gets rid of the race condition and is cross-platform:</p> <pre><code>import os import errno def make_sure_path_exists(path): try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise </code></pre> <p>In other words, we try to create the directories, but if they already exist we ignore the error. On the other hand, any other error gets reported. For example, if you create dir 'a' beforehand and remove all permissions from it, you will get an OSError raised with errno.EACCES (Permission denied, error 13).</p>
434
2011-02-17T17:17:25Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
14,364,249
<h3>Python 2.7:</h3> <p>While a naive solution may first use <a href="https://docs.python.org/2/library/os.path.html#os.path.isdir" rel="nofollow" title="os.path.isdir"><code>os.path.isdir</code></a> followed by <a href="https://docs.python.org/2/library/os.html#os.makedirs" rel="nofollow" title="os.makedirs"><code>os.makedirs</code></a>, the solution below reverses the order of the two operations. In doing so, it handles the possible race condition and also disambiguates files from directories:</p> <pre><code>try: os.makedirs(path) except OSError: if not os.path.isdir(path): raise </code></pre> <p>Capturing the exception and using <code>errno</code> is <em>not</em> so useful because <code>OSError: [Errno 17] File exists</code> is raised for both files and directories.</p> <h3>Python 3.2+:</h3> <pre><code>os.makedirs(path, exist_ok=True) </code></pre> <p>If using Python 3.2+, an optional <a href="https://docs.python.org/3/library/os.html#os.makedirs" rel="nofollow" title="os.makedirs"><code>exist_ok</code></a> parameter is available, with a default value of <code>False</code>. It does not exist in Python 2.x up to 2.7. One can therefore simply specify <code>exist_ok=True</code> in Python 3.2+ to avoid raising an exception if the directory already exists. As such, there is, no need for manual exception handling as with Python 2.7.</p> <p>With regard to the directory's <code>chmod</code> <em>mode</em>, please refer to the documentation.</p>
327
2013-01-16T17:31:19Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
18,562,920
<pre><code>import os if not os.path.isfile("test") and not os.path.isdir("test"): os.mkdir("test") </code></pre>
-3
2013-09-01T21:04:50Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
24,740,135
<p>The <a href="https://docs.python.org/2/library/os.html#files-and-directories">relevant python documentation</a> suggests the use of the <a href="https://docs.python.org/2/library/os.html#files-and-directories">EAFP coding style (Easier to Ask for Forgiveness than Permission)</a>. This means that the code</p> <pre><code>try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise else: print "\nBE CAREFUL! Directory %s already exists." % path </code></pre> <p>is better than the alternative</p> <pre><code>if not os.path.exists(path): os.makedirs(path) else: print "\nBE CAREFUL! Directory %s already exists." % path </code></pre> <p>The documentation suggests this exactly because of the race condition discussed in this thread. In addition, as others mention here, there is a performance advantage in querying once instead of twice the OS. Finally, the argument placed forward, potentially, in favour of the second code in some cases --when the developer knows the environment the application is running-- can only be advocated in the special case that the program has set up a private environment for itself (and other instances of the same program).</p> <p>Even in that case, this is a bad practice and can lead to long useless debugging. For example, the fact we set the permissions for a directory should not leave us with the impression permissions are set appropriately for our purposes. A parent directory could be mounted with other permissions. In general, a program should always work correctly and the programmer should not expect one specific environment.</p>
5
2014-07-14T15:29:07Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
28,100,717
<blockquote> <p><strong>Check if a directory exists and create it if necessary?</strong></p> </blockquote> <p>The direct answer to this is, assuming a simple situation where you don't expect other users or processes to be messing with your directory:</p> <pre><code>if not os.path.exists(d): os.makedirs(d) </code></pre> <p><strong>or</strong> if making the directory is subject to race conditions (i.e. if after checking the path exists, something else may have already made it) do this:</p> <pre><code>import errno try: os.makedirs(d) except OSError as exception: if exception.errno != errno.EEXIST: raise </code></pre> <p>But perhaps an even better approach is to sidestep the resource contention issue, by using temporary directories via <a href="https://docs.python.org/library/tempfile.html#tempfile.mkdtemp" rel="nofollow" title="tempfile.mkdtemp"><code>tempfile</code></a>:</p> <pre><code>import tempfile d = tempfile.mkdtemp() </code></pre> <p>Here's the essentials from the online doc:</p> <blockquote> <pre><code>mkdtemp(suffix='', prefix='tmp', dir=None) User-callable function to create and return a unique temporary directory. The return value is the pathname of the directory. The directory is readable, writable, and searchable only by the creating user. Caller is responsible for deleting the directory when done with it. </code></pre> </blockquote>
4
2015-01-22T23:45:59Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
28,100,757
<h1>Insights on the specifics of this situation</h1> <p>You give a particular file at a certain path and you pull the directory from the file path. Then after making sure you have the directory, you attempt to open a file for reading. To comment on this code:</p> <blockquote> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) </code></pre> </blockquote> <p>We want to avoid overwriting the builtin function, <code>dir</code>. Also, <code>filepath</code> or perhaps <code>fullfilepath</code> is probably a better semantic name than <code>filename</code> so this would be better written:</p> <pre><code>import os filepath = '/my/directory/filename.txt' directory = os.path.dirname(filepath) </code></pre> <p>Your end goal is to open this file, you initially state, for writing, but you're essentially approaching this goal (based on your code) like this, which opens the file for <strong>reading</strong>:</p> <blockquote> <pre><code>if not os.path.exists(directory): os.makedirs(directory) f = file(filename) </code></pre> </blockquote> <h2>Assuming opening for reading</h2> <p>Why would you make a directory for a file that you expect to be there and be able to read? </p> <p>Just attempt to open the file.</p> <pre><code>with open(filepath) as my_file: do_stuff(my_file) </code></pre> <p>If the directory or file isn't there, you'll get an <code>IOError</code> with an associated error number: <code>errno.ENOENT</code> will point to the correct error number regardless of your platform. You can catch it if you want, for example:</p> <pre><code>import errno try: with open(filepath) as my_file: do_stuff(my_file) except IOError as error: if error.errno == errno.ENOENT: print 'ignoring error because directory or file is not there' else: raise </code></pre> <h2>Assuming we're opening for writing</h2> <p>This is <em>probably</em> what you're wanting.</p> <p>In this case, we probably aren't facing any race conditions. So just do as you were, but note that for writing, you need to open with the <code>w</code> mode (or <code>a</code> to append). It's also a Python best practice to use the context manager for opening files.</p> <pre><code>import os if not os.path.exists(directory): os.makedirs(directory) with open(filepath, 'w') as my_file: do_stuff(my_file) </code></pre> <p>However, say we have several Python processes that attempt to put all their data into the same directory. Then we may have contention over creation of the directory. In that case it's best to wrap the <code>makedirs</code> call in a try-except block.</p> <pre><code>import os import errno if not os.path.exists(directory): try: os.makedirs(directory) except OSError as error: if error.errno != errno.EEXIST: raise with open(filepath, 'w') as my_file: do_stuff(my_file) </code></pre>
15
2015-01-22T23:49:18Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
28,997,083
<p>In Python 3.4 you can also use the <a href="https://docs.python.org/3/library/pathlib.html">brand new <code>pathlib</code> module</a>:</p> <pre><code>from pathlib import Path path = Path("/my/directory/filename.txt") try: if not path.parent.exists(): path.parent.mkdir(parents=True) except OSError: # handle error; you can also catch specific errors like # FileExistsError and so on. </code></pre>
7
2015-03-11T20:50:01Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
35,262,209
<p>I saw <a href="http://stackoverflow.com/a/5032238/3051142">Heikki Toivonen</a> and <a href="http://stackoverflow.com/a/14364249">A-B-B</a>'s answers and thought of this variation. What do you think?</p> <pre><code>import os import errno def make_sure_path_exists(path): try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST or not os.path.isdir(path): raise </code></pre>
2
2016-02-08T04:08:06Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
36,289,129
<p>For a one-liner solution, you can use <code>IPython.utils.path.ensure_dir_exists()</code>:</p> <pre><code>from IPython.utils.path import ensure_dir_exists ensure_dir_exists(dir) </code></pre> <p>From the <a href="https://ipython.org/ipython-doc/3/api/generated/IPython.utils.path.html#IPython.utils.path.ensure_dir_exists" rel="nofollow">documentation</a>: <em>Ensure that a directory exists. If it doesn’t exist, try to create it and protect against a race condition if another process is doing the same.</em></p>
3
2016-03-29T15:50:53Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
37,703,074
<p>You can use os.listdir for this:</p> <pre><code>import os if 'dirName' in os.listdir('parentFolderPath') print('Directory Exists') </code></pre>
2
2016-06-08T12:52:46Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
39,205,326
<pre><code>import os os.system("mkdir -p ./testdir") </code></pre> <p>-p does all the work for you, why go into all this try/catch stuff when both linux and windows powershell have mkdir -p for years. The only reason to do the check separately is if you want to print the info to a log or screen.</p>
0
2016-08-29T11:34:25Z
[ "python", "exception", "directory" ]
How to check if a directory exists and create it if necessary?
273,192
<p>What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:</p> <pre><code>filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) </code></pre> <p>Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:</p> <pre><code>def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) </code></pre> <p>Is there a flag for "open", that makes this happen automatically?</p>
1,739
2008-11-07T18:56:45Z
39,479,473
<p>You can use <a href="https://docs.python.org/2/distutils/apiref.html#distutils.dir_util.mkpath" rel="nofollow"><code>mkpath</code></a></p> <pre><code># Create a directory and any missing ancestor directories. # If the directory already exists, do nothing. from distutils.dir_util import mkpath mkpath("test") </code></pre> <p>Note that it will create the ancestor directories as well. </p> <p>It works for Python 2 and 3.</p>
0
2016-09-13T21:44:56Z
[ "python", "exception", "directory" ]
Access second result set of stored procedure with SQL or other work-around? Python\pyodbc
273,203
<p>I'm using python\pyodbc and would like to access the second result set of a stored procedure. As near as I can tell, pyodbc does not support multiple result sets. Additionally, I can't modify the stored procedure. Are there any options to access the second result set using SQL or some other work-around? Perhaps create a second stored procedure that only returns the second result set of the first?</p>
6
2008-11-07T18:58:47Z
273,386
<p>There are a few possible methods <a href="http://www.sommarskog.se/share_data.html" rel="nofollow">here</a>. If the result sets are all the same, you might be able to use the INSERT...EXEC method. Otherwise OPENQUERY might work.</p>
0
2008-11-07T19:43:29Z
[ "python", "sql", "pyodbc" ]
Access second result set of stored procedure with SQL or other work-around? Python\pyodbc
273,203
<p>I'm using python\pyodbc and would like to access the second result set of a stored procedure. As near as I can tell, pyodbc does not support multiple result sets. Additionally, I can't modify the stored procedure. Are there any options to access the second result set using SQL or some other work-around? Perhaps create a second stored procedure that only returns the second result set of the first?</p>
6
2008-11-07T18:58:47Z
313,665
<p>No need for anything fancy. Just use nextset:</p> <pre><code> import pyodbc db = pyodbc.connect ("") q = db.cursor () q.execute (""" SELECT TOP 5 * FROM INFORMATION_SCHEMA.TABLES SELECT TOP 10 * FROM INFORMATION_SCHEMA.COLUMNS """) tables = q.fetchall () q.nextset () columns = q.fetchall () assert len (tables) == 5 assert len (columns) == 10 </code></pre>
6
2008-11-24T08:31:21Z
[ "python", "sql", "pyodbc" ]
Python 3.0 and language evolution
273,524
<p>Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity?</p> <p>Also, do you believe that this is how programming languages should evolve or is the price to pay simply too high?</p>
13
2008-11-07T20:23:14Z
273,543
<p>C# and the .NET framework broke compatibility between versions 1.0 and 1.1 as well as between 1.1 and 2.0. Running applications in different versions required having multiple versions of the .NET runtime installed.</p> <p>At least they did include an upgrade wizard to upgrade source from one version to the next (it worked for most of our code).</p>
4
2008-11-07T20:27:16Z
[ "python", "programming-languages", "python-3.x" ]
Python 3.0 and language evolution
273,524
<p>Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity?</p> <p>Also, do you believe that this is how programming languages should evolve or is the price to pay simply too high?</p>
13
2008-11-07T20:23:14Z
273,547
<p>Perl 6 is also going through this type of split right now. Perl 5 programs won't run directly on Perl 6, but there will be a translator to translate the code into a form that may work (I don't think it can handle 100% of the cases).</p> <p><a href="http://en.wikipedia.org/wiki/Perl_6" rel="nofollow">Perl 6</a> even has its own article on Wikipedia.</p>
1
2008-11-07T20:28:09Z
[ "python", "programming-languages", "python-3.x" ]
Python 3.0 and language evolution
273,524
<p>Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity?</p> <p>Also, do you believe that this is how programming languages should evolve or is the price to pay simply too high?</p>
13
2008-11-07T20:23:14Z
273,554
<p>First, here is a <a href="http://video.google.com/videoplay?docid=1189446823303316785" rel="nofollow">video talk</a> about the changes Python will go through. Second, changes are no good. Third, I for one welcome evolution and believe it is necessary.</p>
1
2008-11-07T20:30:00Z
[ "python", "programming-languages", "python-3.x" ]
Python 3.0 and language evolution
273,524
<p>Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity?</p> <p>Also, do you believe that this is how programming languages should evolve or is the price to pay simply too high?</p>
13
2008-11-07T20:23:14Z
273,571
<p>The only language I can think of to attempt such a mid-stream change would be Perl. Of course, Python is beating Perl to that particular finish line by releasing first. It should be noted, however, that Perl's changes are much more extensive than Python's and likely will be harder to detangle.</p> <p>(There's a price for Perl's "There's More Than One Way To Do It" philosophy.)</p> <p>There are examples like the changes from version to version of .NET-based languages (ironic, considering the whole point of .NET was supposed to be API stability and cross-platform compatibility). However, I would hardly call those languages "mature"; it's always been more of a design-on-the-go, build-the-plane-as-we-fly approach to things.</p> <p>Or, as I tend to think of it, most languages come from either "organic growth" or "engineered construction." Perl is the perfect example of organic growth; it started as a fancy text processing tool ala awk/sed and grew into a full language.</p> <p>Python, on the other hand, is much more engineered. Spend a bit of time wandering around the extensive whitepapers on their website to see the extensive debate that goes into every even minor change to the language's syntax and implementation.</p> <p>The idea of making these sorts of far-reaching changes is somewhat new to programming languages because programming languages themselves have changed in nature. It used to be that programming methodologies changed only when a new processor came out that had a new instruction set. The early languages tended to either be so low-level and married to assembly language (e.g. C) or so utterly dynamic in nature (Forth, Lisp) that such a mid-stream change wouldn't even come up as a consideration.</p> <p>As to whether or not the changes are good ones, I'm not sure. I tend to have faith in the people guiding Python's development, however; the changes in the language thus far have been largely for the better.</p> <p>I think in the days to come the Global Interpreter Lock will prove more central than syntax changes. Though the new multiprocessor library might alleviate most of that.</p>
16
2008-11-07T20:37:22Z
[ "python", "programming-languages", "python-3.x" ]
Python 3.0 and language evolution
273,524
<p>Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity?</p> <p>Also, do you believe that this is how programming languages should evolve or is the price to pay simply too high?</p>
13
2008-11-07T20:23:14Z
273,576
<p>The python team has worked very hard to make the lack of backward compatibility as painless as possible, to the point where the 2.6 release of python was created with a mind towards a painless upgrade process. Once you have upgraded to 2.6 there are scripts that you can run that will move you to 3.0 without issue. </p>
9
2008-11-07T20:37:50Z
[ "python", "programming-languages", "python-3.x" ]
Python 3.0 and language evolution
273,524
<p>Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity?</p> <p>Also, do you believe that this is how programming languages should evolve or is the price to pay simply too high?</p>
13
2008-11-07T20:23:14Z
273,646
<p>In the Lisp world it has happened a few times. of course, the language is so dynamic that usually evolution is simply deprecating part of the standard library and making standard another part.</p> <p>also, Lua 4 to 5 was pretty significant; but the language core is so minimal that even wide-reaching changes are documented in a couple of pages.</p>
2
2008-11-07T21:09:55Z
[ "python", "programming-languages", "python-3.x" ]
Python 3.0 and language evolution
273,524
<p>Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity?</p> <p>Also, do you believe that this is how programming languages should evolve or is the price to pay simply too high?</p>
13
2008-11-07T20:23:14Z
273,661
<p>It's worth mentioning that backward compatibility incurs costs of its own. In some cases it's almost impossible to evolve a language in the ideal way if 100% backward compatibility is required. Java's implementation of generics (which erases type information at compile-time in order to be backwardly-compatible) is a good example of how implementing features with 100% backward compatibility can result in a sub-optimal language feature.</p> <p>So loosely speaking, it can come down to a choice between a poorly implemented new feature that's backwardly compatible, or a nicely implemented new feature that's not. In many cases, the latter is a better choice, particularly if there are tools that can automatically translate incompatible code.</p>
7
2008-11-07T21:17:04Z
[ "python", "programming-languages", "python-3.x" ]
Python 3.0 and language evolution
273,524
<p>Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity?</p> <p>Also, do you believe that this is how programming languages should evolve or is the price to pay simply too high?</p>
13
2008-11-07T20:23:14Z
273,685
<p>I think there are many examples of backward compatibility breakages. Many of the languages that did this were either small or died out along the way.</p> <p>Many examples of this involved renaming the language.</p> <p>Algol 60 and Algol 68 were so different that the meetings on Algol 68 broke up into factions. The Algol 68 faction, the Pascal faction and the PL/I faction. </p> <p>Wirth's Pascal morphed into Modula-3. It was very similar to pascal -- very similar syntax and semantics -- but several new features. Was that really a Pascal-2 with no backward compatibility?</p> <p>The Lisp to Scheme thing involved a rename.</p> <p>If you track down a scan of the old <a href="http://cm.bell-labs.com/cm/cs/who/dmr/bintro.html">B programming language</a> manual, you'll see that the evolution to C looks kind of incremental -- not radical -- but it did break compatibility.</p> <p>Fortran existed in many forms. I don't know for sure, but I think that Digital's Fortran 90 for VAX/VMS wasn't completely compatible with ancient Fortran IV programs.</p> <p>RPG went through major upheavals -- I think that there are really two incompatible languages called RPG.</p> <p><strong>Bottom Line</strong> I think that <em>thinking</em> and <em>learning</em> are inevitable. You have three responses to learning the limitations of a language.</p> <ol> <li><p>Invent a new language that's utterly incompatible.</p></li> <li><p>Incremental chagne until you are forced to invent a new language.</p></li> <li><p>Break compatibility in a controlled, thoughtful way.</p></li> </ol> <p>I think that #1 and #2 are both coward's ways out. Chucking the old is easier than attempting to preserve it. Preserving every nuanced feature (no matter how bad) is a lot of work, some of it of little or no value.</p> <p>Commercial enterprises opt for cowardly approaches in the name of "new marketing" or "preserving our existing customers". That's why commercial software ventures aren't hot-beds of innovation. </p> <p>I think that <strong>only</strong> open-source projects can be embrace innovation in the way that the Python community is tackling this change.</p>
6
2008-11-07T21:24:29Z
[ "python", "programming-languages", "python-3.x" ]
Python 3.0 and language evolution
273,524
<p>Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity?</p> <p>Also, do you believe that this is how programming languages should evolve or is the price to pay simply too high?</p>
13
2008-11-07T20:23:14Z
273,688
<p>The price of insisting on near-absolute backwards compatibility is just too high. Spend two minutes programming in C++ if you want to see why.</p>
13
2008-11-07T21:25:59Z
[ "python", "programming-languages", "python-3.x" ]
Python 3.0 and language evolution
273,524
<p>Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity?</p> <p>Also, do you believe that this is how programming languages should evolve or is the price to pay simply too high?</p>
13
2008-11-07T20:23:14Z
273,994
<p>Wouldn't VB6 to VB.net be the biggest example of this? Or do you all consider them two separate languages? </p>
4
2008-11-07T23:29:44Z
[ "python", "programming-languages", "python-3.x" ]
Python 3.0 and language evolution
273,524
<p>Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity?</p> <p>Also, do you believe that this is how programming languages should evolve or is the price to pay simply too high?</p>
13
2008-11-07T20:23:14Z
274,338
<p>gcc regularly changes how it handles C++ almost every minor release. Of course, this is more a consequence of gcc tightening how they follow the rules, and less of C++ itself changing.</p>
0
2008-11-08T04:03:43Z
[ "python", "programming-languages", "python-3.x" ]
Python 3.0 and language evolution
273,524
<p>Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity?</p> <p>Also, do you believe that this is how programming languages should evolve or is the price to pay simply too high?</p>
13
2008-11-07T20:23:14Z
427,917
<p>The new version of the Ruby programming language will also break compatibility.</p> <p>And think of the libraries one might use: gtk, Qt, and so on (they also have incompatible versions).</p> <p>I think incompatibility is necessary sometimes (but not too often) to support progress.</p>
0
2009-01-09T12:38:57Z
[ "python", "programming-languages", "python-3.x" ]
python, basic question on loops
273,612
<p>It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like;</p> <p>"loop again? y/n"</p>
2
2008-11-07T20:55:33Z
273,618
<pre><code>while True: func() answer = raw_input( "Loop again? " ) if answer != 'y': break </code></pre>
13
2008-11-07T20:58:56Z
[ "python", "loops" ]
python, basic question on loops
273,612
<p>It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like;</p> <p>"loop again? y/n"</p>
2
2008-11-07T20:55:33Z
273,620
<pre><code>keepLooping = True while keepLooping: # do stuff here # Prompt the user to continue q = raw_input("Keep looping? [yn]: ") if not q.startswith("y"): keepLooping = False </code></pre>
6
2008-11-07T20:59:57Z
[ "python", "loops" ]
python, basic question on loops
273,612
<p>It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like;</p> <p>"loop again? y/n"</p>
2
2008-11-07T20:55:33Z
273,677
<p>There are two usual approaches, both already mentioned, which amount to:</p> <pre><code>while True: do_stuff() # and eventually... break; # break out of the loop </code></pre> <p>or</p> <pre><code>x = True while x: do_stuff() # and eventually... x = False # set x to False to break the loop </code></pre> <p>Both will work properly. From a "sound design" perspective it's best to use the second method because 1) <code>break</code> can have counterintuitive behavior in nested scopes in some languages; 2) the first approach is counter to the intended use of "while"; 3) your routines should always have a single point of exit</p>
5
2008-11-07T21:22:20Z
[ "python", "loops" ]
python, basic question on loops
273,612
<p>It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like;</p> <p>"loop again? y/n"</p>
2
2008-11-07T20:55:33Z
321,040
<pre><code>While raw_input("loop again? y/n ") != 'n': do_stuff() </code></pre>
1
2008-11-26T15:12:09Z
[ "python", "loops" ]
Is there a cross-platform way of getting information from Python's OSError?
273,698
<p>On a simple directory creation operation for example, I can make an OSError like this:</p> <p>(Ubuntu Linux)</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.mkdir('foo') &gt;&gt;&gt; os.mkdir('foo') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; OSError: [Errno 17] File exists: 'foo' </code></pre> <p>Now I can catch that error like this:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.mkdir('foo') &gt;&gt;&gt; try: ... os.mkdir('foo') ... except OSError, e: ... print e.args ... (17, 'File exists') </code></pre> <p>Is there a cross-platform way that I can know that that the 17 or the 'File Exists' will always mean the same thing so that I can act differently depending on the situation?</p> <p>(This came up <a href="http://stackoverflow.com/questions/273192/python-best-way-to-create-directory-if-it-doesnt-exist-for-file-write">during another question</a>.)</p>
31
2008-11-07T21:30:18Z
273,872
<p>The <code>errno</code> attribute on the error should be the same on all platforms. You will get <code>WindowsError</code> exceptions on Windows, but since this is a subclass of OSError the same "<code>except OSError:</code>" block will catch it. Windows does have its own error codes, and these are accessible as <code>.winerror</code>, but the <code>.errno</code> attribute should still be present, and usable in a cross-platform way.</p> <p>Symbolic names for the various error codes can be found in the <code>errno</code> module. For example,</p> <pre><code>import os, errno try: os.mkdir('test') except OSError, e: if e.errno == errno.EEXIST: # Do something </code></pre> <p>You can also perform the reverse lookup (to find out what code you should be using) with <code>errno.errorcode</code>. That is:</p> <pre><code>&gt;&gt;&gt; errno.errorcode[17] 'EEXIST' </code></pre>
48
2008-11-07T22:39:59Z
[ "python", "exception", "cross-platform" ]
How do I Create an instance of a class in another class in Python
273,937
<p>I am trying to learn Python and WxPython. I have been a SAS programmer for years. This OOP stuff is slowly coming together but I am still fuzzy on a lot of the concepts. Below is a section of code. I am trying to use a button click to create an instance of another class. Specifically-I have my main panel in one class and I wanted to instance a secondary panel when a user clicked on one of the menu items on the main panel. I made all of this work when the secondary panel was just a function. I can't seem to get ti to work as a class. </p> <p>Here is the code</p> <pre><code>import wx class mainPanel(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450)) wx.Panel(self,-1) wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10)) menubar = wx.MenuBar() parser = wx.Menu() one =wx.MenuItem(parser,1,'&amp;Extract Tables with One Heading or Label') two =wx.MenuItem(parser,1,'&amp;Extract Tables with Two Headings or Labels') three =wx.MenuItem(parser,1,'&amp;Extract Tables with Three Headings or Labels') four =wx.MenuItem(parser,1,'&amp;Extract Tables with Four Headings or Labels') quit = wx.MenuItem(parser, 2, '&amp;Quit\tCtrl+Q') parser.AppendItem(one) parser.AppendItem(two) parser.AppendItem(three) parser.AppendItem(four) parser.AppendItem(quit) menubar.Append(parser, '&amp;Table Parsers') textRip = wx.Menu() section =wx.MenuItem(parser,1,'&amp;Extract Text With Section Headings') textRip.AppendItem(section) menubar.Append(textRip, '&amp;Text Rippers') dataHandling = wx.Menu() deHydrate =wx.MenuItem(dataHandling,1,'&amp;Extract Data from Tables') dataHandling.AppendItem(deHydrate) menubar.Append(dataHandling, '&amp;Data Extraction') self.Bind(wx.EVT_MENU, self.OnQuit, id=2) </code></pre> <h1>this is where I think I am being clever by using a button click to create an instance</h1> <h1>of subPanel.</h1> <pre><code> self.Bind(wx.EVT_MENU, self.subPanel(None, -1, 'TEST'),id=1) self.SetMenuBar(menubar) self.Centre() self.Show(True) def OnQuit(self, event): self.Close() class subPanel(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450)) wx.Panel(self,-1) wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10)) getDirectory = wx.Button(panel, -1, "Get Directory Path", pos=(20,350)) getDirectory.SetDefault() getTerm1 = wx.Button(panel, -1, "Get Search Term", pos=(20,400)) getTerm1.SetDefault() #getDirectory.Bind(wx.EVT_BUTTON, getDirectory.OnClick, getDirectory.button) self.Centre() self.Show(True) app = wx.App() mainPanel(None, -1, '') app.MainLoop() </code></pre>
2
2008-11-07T23:03:53Z
274,004
<p>I don't know wxWidgets, but based on what I know of Python, I'm guessing that you need to change:</p> <pre><code>self.Bind(wx.EVT_MENU, self.subPanel(None, -1, 'TEST'),id=1) </code></pre> <p>to:</p> <pre><code>self.Bind(wx.EVT_MENU, subPanel(None, -1, 'TEST'),id=1) </code></pre> <p>"subPanel" is a globally defined class, not a member of "self" (which is a mainPanel).</p> <p>Edit: Ah, "Bind" seems to bind an action to a function, so you need to give it a function that creates the other class. Try the following. It still doesn't work, but at least it now crashes during the subPanel creation.</p> <pre><code>self.Bind(wx.EVT_MENU, lambda(x): subPanel(None, -1, 'TEST'),id=1) </code></pre>
1
2008-11-07T23:34:25Z
[ "python", "oop", "wxpython" ]
How do I Create an instance of a class in another class in Python
273,937
<p>I am trying to learn Python and WxPython. I have been a SAS programmer for years. This OOP stuff is slowly coming together but I am still fuzzy on a lot of the concepts. Below is a section of code. I am trying to use a button click to create an instance of another class. Specifically-I have my main panel in one class and I wanted to instance a secondary panel when a user clicked on one of the menu items on the main panel. I made all of this work when the secondary panel was just a function. I can't seem to get ti to work as a class. </p> <p>Here is the code</p> <pre><code>import wx class mainPanel(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450)) wx.Panel(self,-1) wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10)) menubar = wx.MenuBar() parser = wx.Menu() one =wx.MenuItem(parser,1,'&amp;Extract Tables with One Heading or Label') two =wx.MenuItem(parser,1,'&amp;Extract Tables with Two Headings or Labels') three =wx.MenuItem(parser,1,'&amp;Extract Tables with Three Headings or Labels') four =wx.MenuItem(parser,1,'&amp;Extract Tables with Four Headings or Labels') quit = wx.MenuItem(parser, 2, '&amp;Quit\tCtrl+Q') parser.AppendItem(one) parser.AppendItem(two) parser.AppendItem(three) parser.AppendItem(four) parser.AppendItem(quit) menubar.Append(parser, '&amp;Table Parsers') textRip = wx.Menu() section =wx.MenuItem(parser,1,'&amp;Extract Text With Section Headings') textRip.AppendItem(section) menubar.Append(textRip, '&amp;Text Rippers') dataHandling = wx.Menu() deHydrate =wx.MenuItem(dataHandling,1,'&amp;Extract Data from Tables') dataHandling.AppendItem(deHydrate) menubar.Append(dataHandling, '&amp;Data Extraction') self.Bind(wx.EVT_MENU, self.OnQuit, id=2) </code></pre> <h1>this is where I think I am being clever by using a button click to create an instance</h1> <h1>of subPanel.</h1> <pre><code> self.Bind(wx.EVT_MENU, self.subPanel(None, -1, 'TEST'),id=1) self.SetMenuBar(menubar) self.Centre() self.Show(True) def OnQuit(self, event): self.Close() class subPanel(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450)) wx.Panel(self,-1) wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10)) getDirectory = wx.Button(panel, -1, "Get Directory Path", pos=(20,350)) getDirectory.SetDefault() getTerm1 = wx.Button(panel, -1, "Get Search Term", pos=(20,400)) getTerm1.SetDefault() #getDirectory.Bind(wx.EVT_BUTTON, getDirectory.OnClick, getDirectory.button) self.Centre() self.Show(True) app = wx.App() mainPanel(None, -1, '') app.MainLoop() </code></pre>
2
2008-11-07T23:03:53Z
274,145
<p>You should handle the button click event, and create the panel in your button handler (like you already do with your OnQuit method).</p> <p>I think the following code basically does what you're after -- creates a new Frame when the button is clicked/menu item is selected.</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self, parent, title="My Frame", num=1): self.num = num wx.Frame.__init__(self, parent, -1, title) panel = wx.Panel(self) button = wx.Button(panel, -1, "New Panel") button.SetPosition((15, 15)) self.Bind(wx.EVT_BUTTON, self.OnNewPanel, button) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) # Now create a menu menubar = wx.MenuBar() self.SetMenuBar(menubar) # Panel menu panel_menu = wx.Menu() # The menu item menu_newpanel = wx.MenuItem(panel_menu, wx.NewId(), "&amp;New Panel", "Creates a new panel", wx.ITEM_NORMAL) panel_menu.AppendItem(menu_newpanel) menubar.Append(panel_menu, "&amp;Panels") # Bind the menu event self.Bind(wx.EVT_MENU, self.OnNewPanel, menu_newpanel) def OnNewPanel(self, event): panel = MyFrame(self, "Panel %s" % self.num, self.num+1) panel.Show() def OnCloseWindow(self, event): self.Destroy() def main(): application = wx.PySimpleApp() frame = MyFrame(None) frame.Show() application.MainLoop() if __name__ == "__main__": main() </code></pre> <p><hr /></p> <p><strong>Edit</strong>: Added code to do this from a menu.</p>
1
2008-11-08T01:10:57Z
[ "python", "oop", "wxpython" ]
How do I Create an instance of a class in another class in Python
273,937
<p>I am trying to learn Python and WxPython. I have been a SAS programmer for years. This OOP stuff is slowly coming together but I am still fuzzy on a lot of the concepts. Below is a section of code. I am trying to use a button click to create an instance of another class. Specifically-I have my main panel in one class and I wanted to instance a secondary panel when a user clicked on one of the menu items on the main panel. I made all of this work when the secondary panel was just a function. I can't seem to get ti to work as a class. </p> <p>Here is the code</p> <pre><code>import wx class mainPanel(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450)) wx.Panel(self,-1) wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10)) menubar = wx.MenuBar() parser = wx.Menu() one =wx.MenuItem(parser,1,'&amp;Extract Tables with One Heading or Label') two =wx.MenuItem(parser,1,'&amp;Extract Tables with Two Headings or Labels') three =wx.MenuItem(parser,1,'&amp;Extract Tables with Three Headings or Labels') four =wx.MenuItem(parser,1,'&amp;Extract Tables with Four Headings or Labels') quit = wx.MenuItem(parser, 2, '&amp;Quit\tCtrl+Q') parser.AppendItem(one) parser.AppendItem(two) parser.AppendItem(three) parser.AppendItem(four) parser.AppendItem(quit) menubar.Append(parser, '&amp;Table Parsers') textRip = wx.Menu() section =wx.MenuItem(parser,1,'&amp;Extract Text With Section Headings') textRip.AppendItem(section) menubar.Append(textRip, '&amp;Text Rippers') dataHandling = wx.Menu() deHydrate =wx.MenuItem(dataHandling,1,'&amp;Extract Data from Tables') dataHandling.AppendItem(deHydrate) menubar.Append(dataHandling, '&amp;Data Extraction') self.Bind(wx.EVT_MENU, self.OnQuit, id=2) </code></pre> <h1>this is where I think I am being clever by using a button click to create an instance</h1> <h1>of subPanel.</h1> <pre><code> self.Bind(wx.EVT_MENU, self.subPanel(None, -1, 'TEST'),id=1) self.SetMenuBar(menubar) self.Centre() self.Show(True) def OnQuit(self, event): self.Close() class subPanel(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450)) wx.Panel(self,-1) wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10)) getDirectory = wx.Button(panel, -1, "Get Directory Path", pos=(20,350)) getDirectory.SetDefault() getTerm1 = wx.Button(panel, -1, "Get Search Term", pos=(20,400)) getTerm1.SetDefault() #getDirectory.Bind(wx.EVT_BUTTON, getDirectory.OnClick, getDirectory.button) self.Centre() self.Show(True) app = wx.App() mainPanel(None, -1, '') app.MainLoop() </code></pre>
2
2008-11-07T23:03:53Z
274,160
<p>You need an event handler in your bind expression</p> <pre><code>self.bind(wx.EVT_MENU, subPanel(None, -1, 'TEST'),id=1) </code></pre> <p>needs to be changed to:</p> <pre><code>self.bind(wx.EVT_MENU, &lt;event handler&gt;, &lt;id of menu item&gt;) </code></pre> <p>where your event handler responds to the event and instantiates the subpanel:</p> <pre><code>def OnMenuItem(self, evt): #don't forget the evt sp = SubPanel(self, wx.ID_ANY, 'TEST') #I assume you will add it to a sizer #if you aren't... you should test_sizer.Add(sp, 1, wx.EXPAND) #force the frame to refresh the sizers: self.Layout() </code></pre> <p>Alternatively, you can instantiate the subpanel in your frame's <code>__init__</code> and call a <code>subpanel.Hide()</code> after instantiation, and then your menuitem event handler and call a show on the panel <code>subpanel.Show()</code></p> <p>Edit: Here is some code that will do what I think that you are asking:</p> <pre><code>#!usr/bin/env python import wx class TestFrame(wx.Frame): def __init__(self, parent, *args, **kwargs): wx.Frame.__init__(self, parent, *args, **kwargs) framesizer = wx.BoxSizer(wx.VERTICAL) mainpanel = MainPanel(self, wx.ID_ANY) self.subpanel = SubPanel(self, wx.ID_ANY) self.subpanel.Hide() framesizer.Add(mainpanel, 1, wx.EXPAND) framesizer.Add(self.subpanel, 1, wx.EXPAND) self.SetSizerAndFit(framesizer) class MainPanel(wx.Panel): def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) panelsizer = wx.BoxSizer(wx.VERTICAL) but = wx.Button(self, wx.ID_ANY, "Add") self.Bind(wx.EVT_BUTTON, self.OnAdd, but) self.panel_shown = False panelsizer.Add(but, 0) self.SetSizer(panelsizer) def OnAdd(self, evt): if not self.panel_shown: self.GetParent().subpanel.Show() self.GetParent().Fit() self.GetParent().Layout() self.panel_shown = True else: self.GetParent().subpanel.Hide() self.GetParent().Fit() self.GetParent().Layout() self.panel_shown = False class SubPanel(wx.Panel): def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) spsizer = wx.BoxSizer(wx.VERTICAL) text = wx.StaticText(self, wx.ID_ANY, label='I am a subpanel') spsizer.Add(text, 1, wx.EXPAND) self.SetSizer(spsizer) if __name__ == '__main__': app = wx.App() frame = TestFrame(None, wx.ID_ANY, "Test Frame") frame.Show() app.MainLoop() </code></pre>
0
2008-11-08T01:19:19Z
[ "python", "oop", "wxpython" ]
How do I resize an image using PIL and maintain its aspect ratio?
273,946
<p>Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.</p>
196
2008-11-07T23:08:04Z
273,962
<p>Define a maximum size. Then, compute a resize ratio by taking <code>min(maxwidth/width, maxheight/height)</code>.</p> <p>The proper size is <code>oldsize*ratio</code>.</p> <p>There is of course also a library method to do this: the method <code>Image.thumbnail</code>.<br> Below is an (edited) example from the <a href="http://effbot.org/imagingbook/introduction.htm">PIL documentation</a>.</p> <pre><code>import os, sys import Image size = 128, 128 for infile in sys.argv[1:]: outfile = os.path.splitext(infile)[0] + ".thumbnail" if infile != outfile: try: im = Image.open(infile) im.thumbnail(size, Image.ANTIALIAS) im.save(outfile, "JPEG") except IOError: print "cannot create thumbnail for '%s'" % infile </code></pre>
246
2008-11-07T23:15:37Z
[ "python", "image", "python-imaging-library", "thumbnails" ]
How do I resize an image using PIL and maintain its aspect ratio?
273,946
<p>Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.</p>
196
2008-11-07T23:08:04Z
364,789
<p>If you are trying to maintain the same aspect ratio, then wouldn't you resize by some percentage of the original size?</p> <p>For example, half the original size</p> <pre><code>half = 0.5 out = im.resize( [int(half * s) for s in im.size] ) </code></pre>
9
2008-12-13T03:43:00Z
[ "python", "image", "python-imaging-library", "thumbnails" ]
How do I resize an image using PIL and maintain its aspect ratio?
273,946
<p>Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.</p>
196
2008-11-07T23:08:04Z
451,580
<p>This script will resize an image (somepic.jpg) using PIL (Python Imaging Library) to a width of 300 pixels and a height proportional to the new width. It does this by determining what percentage 300 pixels is of the original width (img.size[0]) and then multiplying the original height (img.size[1]) by that percentage. Change "basewidth" to any other number to change the default width of your images.</p> <pre><code>import PIL from PIL import Image basewidth = 300 img = Image.open('somepic.jpg') wpercent = (basewidth/float(img.size[0])) hsize = int((float(img.size[1])*float(wpercent))) img = img.resize((basewidth,hsize), PIL.Image.ANTIALIAS) img.save('sompic.jpg') </code></pre>
77
2009-01-16T19:12:07Z
[ "python", "image", "python-imaging-library", "thumbnails" ]
How do I resize an image using PIL and maintain its aspect ratio?
273,946
<p>Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.</p>
196
2008-11-07T23:08:04Z
940,368
<p>I also recommend using PIL's thumbnail method, because it removes all the ratio hassles from you.</p> <p>One important hint, though: Replace</p> <pre><code>im.thumbnail(size) </code></pre> <p>with</p> <pre><code>im.thumbnail(size,Image.ANTIALIAS) </code></pre> <p>by default, PIL uses the Image.NEAREST filter for resizing which results in good performance, but poor quality.</p>
39
2009-06-02T16:03:07Z
[ "python", "image", "python-imaging-library", "thumbnails" ]