title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How do I run "dot" as a command from Python?
955,504
<p>I am using Python on Mac OSX Leopard.</p> <p>I am trying to run the program 'dot' (part of Graphviz) from Python:</p> <pre><code># -*- coding: utf-8 -*- import os print os.environ['PATH'] print os.system("ls &gt;&gt; a.txt") print os.system("dot -o9.png -Tpng ./6.dot") </code></pre> <p>The command "ls" is there just to make sure that python is in the correct directory. It is. The result that I get is:</p> <blockquote> <p>/usr/bin:/bin:/usr/sbin:/sbin 0 32512</p> </blockquote> <p>My understanding is that 32512 error means that python could not find the file, and since the file 6.dot is there (If I run "dot -o9.png -Tpng ./6.dot" from the terminal I receive no error, and 9.png gets produced), I assume Python can't find the dot file.</p> <p>I probably need to add the dot file to the path. But I don't know where is it. If I run: </p> <pre><code>whereis dot </code></pre> <p>I receive no answer.</p> <p>How can I find the dot executable?<br /> Alternatively, can I run the dot program as a command from inside Python?</p>
4
2009-06-05T11:55:09Z
955,616
<p>Two suggestions</p> <ol> <li>Don't use PATH, instead use "which" to just find the executable instead</li> <li>You don't use ";" (semi-colon) to separate paths, but ":" (colon). Once you change this it should be able to find your dot program.</li> </ol> <p>Change this</p> <pre><code>os.environ['PATH'] += ";"+"/usr/local/bin/dot" </code></pre> <p>to this</p> <pre><code>os.environ['PATH'] += ":"+"/usr/local/bin" </code></pre> <p>Then your good.</p> <p>EDIT: Note that I forgot to remove the /dot from the PATH variable myself (oops) - PATH is a colon delimited list of directories.</p>
2
2009-06-05T12:35:39Z
[ "python", "osx", "path", "graphviz", "dot" ]
How do I run "dot" as a command from Python?
955,504
<p>I am using Python on Mac OSX Leopard.</p> <p>I am trying to run the program 'dot' (part of Graphviz) from Python:</p> <pre><code># -*- coding: utf-8 -*- import os print os.environ['PATH'] print os.system("ls &gt;&gt; a.txt") print os.system("dot -o9.png -Tpng ./6.dot") </code></pre> <p>The command "ls" is there just to make sure that python is in the correct directory. It is. The result that I get is:</p> <blockquote> <p>/usr/bin:/bin:/usr/sbin:/sbin 0 32512</p> </blockquote> <p>My understanding is that 32512 error means that python could not find the file, and since the file 6.dot is there (If I run "dot -o9.png -Tpng ./6.dot" from the terminal I receive no error, and 9.png gets produced), I assume Python can't find the dot file.</p> <p>I probably need to add the dot file to the path. But I don't know where is it. If I run: </p> <pre><code>whereis dot </code></pre> <p>I receive no answer.</p> <p>How can I find the dot executable?<br /> Alternatively, can I run the dot program as a command from inside Python?</p>
4
2009-06-05T11:55:09Z
955,619
<p>Instead of:</p> <pre><code>print os.system("dot -o9.png -Tpng ./6.dot") </code></pre> <p>try this:</p> <pre><code>from subprocess import check_call print check_call("dot -o9.png -Tpng ./6.dot") </code></pre> <p>If exit status of dot program is 0, the status is printed. If dot returns non-zero status, it raises CalledProcessError (and shows returned status). If dot doesn't exist in current path, OSError is raised on Linux or WindowsErroor on Windows (I don't know which exception is raised under Mac OS, but I assume OSError).</p> <p>EDIT: Code above will give you the hint if you have no dot executable or 6.dot file in current path settings.</p>
1
2009-06-05T12:38:09Z
[ "python", "osx", "path", "graphviz", "dot" ]
How do I run "dot" as a command from Python?
955,504
<p>I am using Python on Mac OSX Leopard.</p> <p>I am trying to run the program 'dot' (part of Graphviz) from Python:</p> <pre><code># -*- coding: utf-8 -*- import os print os.environ['PATH'] print os.system("ls &gt;&gt; a.txt") print os.system("dot -o9.png -Tpng ./6.dot") </code></pre> <p>The command "ls" is there just to make sure that python is in the correct directory. It is. The result that I get is:</p> <blockquote> <p>/usr/bin:/bin:/usr/sbin:/sbin 0 32512</p> </blockquote> <p>My understanding is that 32512 error means that python could not find the file, and since the file 6.dot is there (If I run "dot -o9.png -Tpng ./6.dot" from the terminal I receive no error, and 9.png gets produced), I assume Python can't find the dot file.</p> <p>I probably need to add the dot file to the path. But I don't know where is it. If I run: </p> <pre><code>whereis dot </code></pre> <p>I receive no answer.</p> <p>How can I find the dot executable?<br /> Alternatively, can I run the dot program as a command from inside Python?</p>
4
2009-06-05T11:55:09Z
955,730
<p>If you also generate your Dot files in Python, <a href="http://code.google.com/p/pydot/" rel="nofollow">pydot</a> does what you want in a more Pythonic way:</p> <pre><code>import pydot dot = pydot.Dot() n1, n2 = pydot.Node("a"), pydot.Node("b") dot.add_node(n1) dot.add_node(n2) dot.add_edge(pydot.Edge(n1,n2)) dot.write_png("graph.png", prog='neato') </code></pre>
2
2009-06-05T13:04:49Z
[ "python", "osx", "path", "graphviz", "dot" ]
How do I run "dot" as a command from Python?
955,504
<p>I am using Python on Mac OSX Leopard.</p> <p>I am trying to run the program 'dot' (part of Graphviz) from Python:</p> <pre><code># -*- coding: utf-8 -*- import os print os.environ['PATH'] print os.system("ls &gt;&gt; a.txt") print os.system("dot -o9.png -Tpng ./6.dot") </code></pre> <p>The command "ls" is there just to make sure that python is in the correct directory. It is. The result that I get is:</p> <blockquote> <p>/usr/bin:/bin:/usr/sbin:/sbin 0 32512</p> </blockquote> <p>My understanding is that 32512 error means that python could not find the file, and since the file 6.dot is there (If I run "dot -o9.png -Tpng ./6.dot" from the terminal I receive no error, and 9.png gets produced), I assume Python can't find the dot file.</p> <p>I probably need to add the dot file to the path. But I don't know where is it. If I run: </p> <pre><code>whereis dot </code></pre> <p>I receive no answer.</p> <p>How can I find the dot executable?<br /> Alternatively, can I run the dot program as a command from inside Python?</p>
4
2009-06-05T11:55:09Z
955,756
<p>Often the solution is in front of us,</p> <pre><code>print os.system("/usr/local/bin/dot -o9.png -Tpng 6.dot") </code></pre> <p>Also you can try for all the dots in a specified folder</p> <pre><code>import glob for filedot in glob.glob('*.dot') print os.system("/usr/local/bin/dot -o9.png -Tpng %(filedot)s"%locals()) #print os.system("/usr/local/bin/dot -o9.png -Tpng %s"%filedot) </code></pre> <p>Edit:</p> <p>I cannot recall btw if it is </p> <pre><code>/usr/local/bin/dot -o9.png -Tpng fdot.dot </code></pre> <p>or</p> <pre><code>/usr/local/bin/dot -o 9.png -Tpng fdot.dot </code></pre>
2
2009-06-05T13:07:52Z
[ "python", "osx", "path", "graphviz", "dot" ]
How do I run "dot" as a command from Python?
955,504
<p>I am using Python on Mac OSX Leopard.</p> <p>I am trying to run the program 'dot' (part of Graphviz) from Python:</p> <pre><code># -*- coding: utf-8 -*- import os print os.environ['PATH'] print os.system("ls &gt;&gt; a.txt") print os.system("dot -o9.png -Tpng ./6.dot") </code></pre> <p>The command "ls" is there just to make sure that python is in the correct directory. It is. The result that I get is:</p> <blockquote> <p>/usr/bin:/bin:/usr/sbin:/sbin 0 32512</p> </blockquote> <p>My understanding is that 32512 error means that python could not find the file, and since the file 6.dot is there (If I run "dot -o9.png -Tpng ./6.dot" from the terminal I receive no error, and 9.png gets produced), I assume Python can't find the dot file.</p> <p>I probably need to add the dot file to the path. But I don't know where is it. If I run: </p> <pre><code>whereis dot </code></pre> <p>I receive no answer.</p> <p>How can I find the dot executable?<br /> Alternatively, can I run the dot program as a command from inside Python?</p>
4
2009-06-05T11:55:09Z
955,759
<p>You should change the PATH line so it includes the directory which contains <code>dot</code>. That directory is <code>/usr/local/bin</code>, without <code>/dot</code>.</p>
2
2009-06-05T13:07:56Z
[ "python", "osx", "path", "graphviz", "dot" ]
How do I run "dot" as a command from Python?
955,504
<p>I am using Python on Mac OSX Leopard.</p> <p>I am trying to run the program 'dot' (part of Graphviz) from Python:</p> <pre><code># -*- coding: utf-8 -*- import os print os.environ['PATH'] print os.system("ls &gt;&gt; a.txt") print os.system("dot -o9.png -Tpng ./6.dot") </code></pre> <p>The command "ls" is there just to make sure that python is in the correct directory. It is. The result that I get is:</p> <blockquote> <p>/usr/bin:/bin:/usr/sbin:/sbin 0 32512</p> </blockquote> <p>My understanding is that 32512 error means that python could not find the file, and since the file 6.dot is there (If I run "dot -o9.png -Tpng ./6.dot" from the terminal I receive no error, and 9.png gets produced), I assume Python can't find the dot file.</p> <p>I probably need to add the dot file to the path. But I don't know where is it. If I run: </p> <pre><code>whereis dot </code></pre> <p>I receive no answer.</p> <p>How can I find the dot executable?<br /> Alternatively, can I run the dot program as a command from inside Python?</p>
4
2009-06-05T11:55:09Z
955,961
<p><code>check_call</code> does not use the same syntax as <code>os.system</code>, so you should try changing the corresponding line this way:</p> <pre><code>print check_call(["dot", "-o9.png", "-Tpng", "./6.dot"]) </code></pre> <p>The executable name is the first item in the array, and each parameter must be in another item of the array. Otherwise you will <em>always</em> get a "No such file" error because there is no executable named "dot -o9.png ..." in your PATH.</p>
1
2009-06-05T13:52:01Z
[ "python", "osx", "path", "graphviz", "dot" ]
How do I run "dot" as a command from Python?
955,504
<p>I am using Python on Mac OSX Leopard.</p> <p>I am trying to run the program 'dot' (part of Graphviz) from Python:</p> <pre><code># -*- coding: utf-8 -*- import os print os.environ['PATH'] print os.system("ls &gt;&gt; a.txt") print os.system("dot -o9.png -Tpng ./6.dot") </code></pre> <p>The command "ls" is there just to make sure that python is in the correct directory. It is. The result that I get is:</p> <blockquote> <p>/usr/bin:/bin:/usr/sbin:/sbin 0 32512</p> </blockquote> <p>My understanding is that 32512 error means that python could not find the file, and since the file 6.dot is there (If I run "dot -o9.png -Tpng ./6.dot" from the terminal I receive no error, and 9.png gets produced), I assume Python can't find the dot file.</p> <p>I probably need to add the dot file to the path. But I don't know where is it. If I run: </p> <pre><code>whereis dot </code></pre> <p>I receive no answer.</p> <p>How can I find the dot executable?<br /> Alternatively, can I run the dot program as a command from inside Python?</p>
4
2009-06-05T11:55:09Z
956,154
<p>One problem is in this line:</p> <pre><code>os.environ['PATH'] += ":"+"/usr/local/bin/dot" </code></pre> <p>You don't put the name of the executable in the path, but the directory containing the executable. So that should be:</p> <pre><code>os.environ['PATH'] += ":"+"/usr/local/bin" </code></pre> <p>And as pointed out in another comment, the arguments to <code>check_call</code> are not the same as <code>os.system</code>.</p>
1
2009-06-05T14:28:02Z
[ "python", "osx", "path", "graphviz", "dot" ]
How do I run "dot" as a command from Python?
955,504
<p>I am using Python on Mac OSX Leopard.</p> <p>I am trying to run the program 'dot' (part of Graphviz) from Python:</p> <pre><code># -*- coding: utf-8 -*- import os print os.environ['PATH'] print os.system("ls &gt;&gt; a.txt") print os.system("dot -o9.png -Tpng ./6.dot") </code></pre> <p>The command "ls" is there just to make sure that python is in the correct directory. It is. The result that I get is:</p> <blockquote> <p>/usr/bin:/bin:/usr/sbin:/sbin 0 32512</p> </blockquote> <p>My understanding is that 32512 error means that python could not find the file, and since the file 6.dot is there (If I run "dot -o9.png -Tpng ./6.dot" from the terminal I receive no error, and 9.png gets produced), I assume Python can't find the dot file.</p> <p>I probably need to add the dot file to the path. But I don't know where is it. If I run: </p> <pre><code>whereis dot </code></pre> <p>I receive no answer.</p> <p>How can I find the dot executable?<br /> Alternatively, can I run the dot program as a command from inside Python?</p>
4
2009-06-05T11:55:09Z
956,429
<p>Try this: </p> <pre><code># -*- coding: utf-8 -*- import os import sys print os.environ['PATH'] os.environ['PATH'] += ":"+"/usr/local/bin" print os.environ['PATH'] print os.getcwd() from subprocess import check_call print check_call(["dot", "-o9.png", "-Tpng", "./6.dot"]) </code></pre> <p>Taken from the question to try and maintain some sort of sanity here.</p>
3
2009-06-05T15:15:33Z
[ "python", "osx", "path", "graphviz", "dot" ]
How do I run "dot" as a command from Python?
955,504
<p>I am using Python on Mac OSX Leopard.</p> <p>I am trying to run the program 'dot' (part of Graphviz) from Python:</p> <pre><code># -*- coding: utf-8 -*- import os print os.environ['PATH'] print os.system("ls &gt;&gt; a.txt") print os.system("dot -o9.png -Tpng ./6.dot") </code></pre> <p>The command "ls" is there just to make sure that python is in the correct directory. It is. The result that I get is:</p> <blockquote> <p>/usr/bin:/bin:/usr/sbin:/sbin 0 32512</p> </blockquote> <p>My understanding is that 32512 error means that python could not find the file, and since the file 6.dot is there (If I run "dot -o9.png -Tpng ./6.dot" from the terminal I receive no error, and 9.png gets produced), I assume Python can't find the dot file.</p> <p>I probably need to add the dot file to the path. But I don't know where is it. If I run: </p> <pre><code>whereis dot </code></pre> <p>I receive no answer.</p> <p>How can I find the dot executable?<br /> Alternatively, can I run the dot program as a command from inside Python?</p>
4
2009-06-05T11:55:09Z
37,060,175
<p>If you are using a GUI such as <code>Spyder</code> then you can simply add the correct bin path into the <code>PYTHONPATH manager</code> options menu.</p> <p>Search for the script location by doing this in the terminal:</p> <pre><code>which programname </code></pre> <p>then take that location (wherever it is), subtract the programname, for example:</p> <pre><code>/home/username/seiscomp3/bin/scart #this is the section of the path that you use /home/username/seiscomp3/bin </code></pre> <p>Then go into the <code>PYTHONPATH manager</code> options menu and add this path. Then restart Spyder and it'll work.</p>
0
2016-05-05T20:59:57Z
[ "python", "osx", "path", "graphviz", "dot" ]
Finding out which functions are available from a class instance in python?
955,533
<p>How do you dynamically find out which functions have been defined from an instance of a class?</p> <p>For example:</p> <pre><code>class A(object): def methodA(self, intA=1): pass def methodB(self, strB): pass a = A() </code></pre> <p>Ideally I want to find out that the instance 'a' has methodA and methodB, and which arguments they take?</p>
1
2009-06-05T12:03:20Z
955,539
<p>Have a look at the <code>inspect</code> module.</p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; inspect.getmembers(a) [('__class__', &lt;class '__main__.A'&gt;), ('__delattr__', &lt;method-wrapper '__delattr__' of A object at 0xb77d48ac&gt;), ('__dict__', {}), ('__doc__', None), ('__getattribute__', &lt;method-wrapper '__getattribute__' of A object at 0xb77d48ac&gt;), ('__hash__', &lt;method-wrapper '__hash__' of A object at 0xb77d48ac&gt;), ('__init__', &lt;method-wrapper '__init__' of A object at 0xb77d48ac&gt;), ('__module__', '__main__'), ('__new__', &lt;built-in method __new__ of type object at 0x8146220&gt;), ('__reduce__', &lt;built-in method __reduce__ of A object at 0xb77d48ac&gt;), ('__reduce_ex__', &lt;built-in method __reduce_ex__ of A object at 0xb77d48ac&gt;), ('__repr__', &lt;method-wrapper '__repr__' of A object at 0xb77d48ac&gt;), ('__setattr__', &lt;method-wrapper '__setattr__' of A object at 0xb77d48ac&gt;), ('__str__', &lt;method-wrapper '__str__' of A object at 0xb77d48ac&gt;), ('__weakref__', None), ('methodA', &lt;bound method A.methodA of &lt;__main__.A object at 0xb77d48ac&gt;&gt;), ('methodB', &lt;bound method A.methodB of &lt;__main__.A object at 0xb77d48ac&gt;&gt;)] &gt;&gt;&gt; inspect.getargspec(a.methodA) (['self', 'intA'], None, None, (1,)) &gt;&gt;&gt; inspect.getargspec(getattr(a, 'methodA')) (['self', 'intA'], None, None, (1,)) &gt;&gt;&gt; print inspect.getargspec.__doc__ Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. &gt;&gt;&gt; print inspect.getmembers.__doc__ Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate. </code></pre>
11
2009-06-05T12:04:51Z
[ "python", "introspection" ]
python web framework focusing on json-oriented web applications
955,751
<p>I'm looking for a python equivalent of ruby's <a href="http://halcyon.rubyforge.org/" rel="nofollow">halcyon</a> - a framework focused on "web service"-type applications rather than html-page-oriented ones. Google brings up a lot of example code and experiments, but I couldn't find anything that people were using in production and hammering on.</p> <p>Failing that, what is the best web framework to use for this purpose? I'm looking for something small and lightweight, emphasising robustness and speed rather than features. Also, by speed I simply want a low latency overhead, not the ability to handle thousands of requests per second.</p>
2
2009-06-05T13:07:25Z
955,828
<p>Why not use django? You can return a json with it, so it's not a problem. At the same time, you get good, well-tested framework... </p>
3
2009-06-05T13:22:58Z
[ "python", "web-services", "json", "web-applications" ]
python web framework focusing on json-oriented web applications
955,751
<p>I'm looking for a python equivalent of ruby's <a href="http://halcyon.rubyforge.org/" rel="nofollow">halcyon</a> - a framework focused on "web service"-type applications rather than html-page-oriented ones. Google brings up a lot of example code and experiments, but I couldn't find anything that people were using in production and hammering on.</p> <p>Failing that, what is the best web framework to use for this purpose? I'm looking for something small and lightweight, emphasising robustness and speed rather than features. Also, by speed I simply want a low latency overhead, not the ability to handle thousands of requests per second.</p>
2
2009-06-05T13:07:25Z
957,453
<p>Based on you comment, it sounds like one of the <a href="http://fewagainstmany.com/blog/python-micro-frameworks-are-all-the-rage" rel="nofollow">microframeworks</a> may be what you're looking for.</p>
4
2009-06-05T18:45:25Z
[ "python", "web-services", "json", "web-applications" ]
Django models: how to return a default value in case of a non-existing foreign-key relationship?
955,815
<p>I am developing a vocabulary training program with Django (German-Swedish). </p> <p>The app's vocabulary data consists of a large number of "vocabulary cards", each of which contains one or more German words or terms that correspond to one or more Swedish terms.</p> <p>Training is only available for registered users, because the app keeps track of the user's performance by saving a <code>score</code> for each vocabulary card.</p> <p>Vocabulary cards have a level (basic, advanced, expert) and any number of tags assigned to them. </p> <p>When a registered user starts a training, the application needs to calculate the user's average scores for each of the levels and tags, so he can make his selection.</p> <p>I have solved this problem by introducing a model named <code>CardByUser</code> that has a <code>score</code> and field and <code>ForeignKey</code> relationships to the models <code>User</code> and <code>Card</code>. Now I can use Django's aggregation function calculate the average scores.</p> <p>The big disadvantage: this works only if there is a <code>CardByUser</code> instance for each and every Card instance that currently exists in the DB, even if the user has only trained 100 cards. My current solution is to create all those <code>CardByUser</code> instances on <code>Card</code> creation and when a user is registered. This is, of course, rather ineficient both in terms of data base memory and of computing time (registering a user takes quite a while). </p> <p>And it seems quite inelegant, which kind of bugs me the most.</p> <p>Is there a better way to do this?</p> <p>Maybe it is possible to tell Django the following when calculating the average score for a <code>Card</code>:</p> <ul> <li>If a <code>CardByUser</code> for the given <code>Card</code> and User exists, use its score.</li> <li>If the <code>CardByUser</code> doesn't exist, use a default value --> the score 0.</li> </ul> <p>Can this be done? If so, how?</p> <p><strong>Edit: Clarification</strong> Thanks S.Lott's for the first answer, but I think that my problem is a bit more complicated. My bad, I'm trying to clarify using some actual code from my models.</p> <pre><code>class Card(models.Model): entry_sv = models.CharField(max_length=200) entry_de = models.CharField(max_length=200) ... more fields ... class CardByUser(models.Model): user = models.ForeignKey(User) card = models.ForeignKey(Card, related_name="user_cards") score = models.IntegerField(default=0) ... more fields ... </code></pre> <p>This means many <code>CardByUser</code> objects are related to a single <code>Card</code>. </p> <p>Now in my view code, I need to create a queryset of <code>CardByUser</code> objects that fulfill the following criteria:</p> <ul> <li>the related <code>Card</code> object's <code>tag</code> field contains a certain string (I now that's not optimal either, but not the focus of my question...)</li> <li>the user is the current user</li> </ul> <p>Then I can aggregate over the scores. My current code looks like this (shortened) :</p> <pre><code>user_cards = CardByUser.objects.filter(user=current_user) .filter(card__tags__contains=tag.name) avg = user_cards_agg.aggregate(Avg('score'))['score__avg'] </code></pre> <p>If a <code>CardByUser</code> for the current user and <code>Card</code> does not exist, it will simply not be included in the aggregation. That's why I create all those <code>CardByUser</code>s with a score of 0.</p> <p>So how could I get rid of those? Any ideas would be appreciated!</p>
3
2009-06-05T13:19:51Z
956,533
<p>This is what methods (and perhaps properties) are for.</p> <pre><code>class OptionalFKWithDefault( models.Model ): another = models.ForeignKey( AnotherModel, blank=True, null=True ) @property def another_score( self ): if self.another is None: return 0 else: return self.another.score </code></pre>
2
2009-06-05T15:32:12Z
[ "python", "django-models", "aggregation" ]
Django models: how to return a default value in case of a non-existing foreign-key relationship?
955,815
<p>I am developing a vocabulary training program with Django (German-Swedish). </p> <p>The app's vocabulary data consists of a large number of "vocabulary cards", each of which contains one or more German words or terms that correspond to one or more Swedish terms.</p> <p>Training is only available for registered users, because the app keeps track of the user's performance by saving a <code>score</code> for each vocabulary card.</p> <p>Vocabulary cards have a level (basic, advanced, expert) and any number of tags assigned to them. </p> <p>When a registered user starts a training, the application needs to calculate the user's average scores for each of the levels and tags, so he can make his selection.</p> <p>I have solved this problem by introducing a model named <code>CardByUser</code> that has a <code>score</code> and field and <code>ForeignKey</code> relationships to the models <code>User</code> and <code>Card</code>. Now I can use Django's aggregation function calculate the average scores.</p> <p>The big disadvantage: this works only if there is a <code>CardByUser</code> instance for each and every Card instance that currently exists in the DB, even if the user has only trained 100 cards. My current solution is to create all those <code>CardByUser</code> instances on <code>Card</code> creation and when a user is registered. This is, of course, rather ineficient both in terms of data base memory and of computing time (registering a user takes quite a while). </p> <p>And it seems quite inelegant, which kind of bugs me the most.</p> <p>Is there a better way to do this?</p> <p>Maybe it is possible to tell Django the following when calculating the average score for a <code>Card</code>:</p> <ul> <li>If a <code>CardByUser</code> for the given <code>Card</code> and User exists, use its score.</li> <li>If the <code>CardByUser</code> doesn't exist, use a default value --> the score 0.</li> </ul> <p>Can this be done? If so, how?</p> <p><strong>Edit: Clarification</strong> Thanks S.Lott's for the first answer, but I think that my problem is a bit more complicated. My bad, I'm trying to clarify using some actual code from my models.</p> <pre><code>class Card(models.Model): entry_sv = models.CharField(max_length=200) entry_de = models.CharField(max_length=200) ... more fields ... class CardByUser(models.Model): user = models.ForeignKey(User) card = models.ForeignKey(Card, related_name="user_cards") score = models.IntegerField(default=0) ... more fields ... </code></pre> <p>This means many <code>CardByUser</code> objects are related to a single <code>Card</code>. </p> <p>Now in my view code, I need to create a queryset of <code>CardByUser</code> objects that fulfill the following criteria:</p> <ul> <li>the related <code>Card</code> object's <code>tag</code> field contains a certain string (I now that's not optimal either, but not the focus of my question...)</li> <li>the user is the current user</li> </ul> <p>Then I can aggregate over the scores. My current code looks like this (shortened) :</p> <pre><code>user_cards = CardByUser.objects.filter(user=current_user) .filter(card__tags__contains=tag.name) avg = user_cards_agg.aggregate(Avg('score'))['score__avg'] </code></pre> <p>If a <code>CardByUser</code> for the current user and <code>Card</code> does not exist, it will simply not be included in the aggregation. That's why I create all those <code>CardByUser</code>s with a score of 0.</p> <p>So how could I get rid of those? Any ideas would be appreciated!</p>
3
2009-06-05T13:19:51Z
964,393
<p>This may not be entirely related to your question, but it looks like <code>CardByUser</code> really should be a many-to-many relationship with an extra field. (see <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships</a>)</p> <p>Maybe you could alter your model this way?</p> <pre><code>class Card(models.Model): entry_sv = models.CharField(max_length=200) entry_de = models.CharField(max_length=200) ... more fields ... users = models.ManyToManyField(User, through='CardByUser') class CardByUser(models.Model): user = models.ForeignKey(User) card = models.ForeignKey(Card) score = models.IntegerField(default=0) </code></pre> <p>Then you won't have to explicitely create CardByUser objects, as this is all taken care of by Django. You should be able to simplify your aggregation query as well:</p> <pre><code>user_cards = Card.objects.filter(users=current_user) .filter(tags__contains=tag.name) ... </code></pre>
1
2009-06-08T11:08:48Z
[ "python", "django-models", "aggregation" ]
How to identify whether a file is normal file or directory using python
955,941
<p>How do you check whether a file is a normal file or a directory using python?</p>
64
2009-06-05T13:47:31Z
955,952
<p><code>os.path.isdir()</code> and <code>os.path.isfile()</code> should give you what you want. See: <a href="http://docs.python.org/library/os.path.html">http://docs.python.org/library/os.path.html</a></p>
93
2009-06-05T13:50:09Z
[ "python" ]
How to identify whether a file is normal file or directory using python
955,941
<p>How do you check whether a file is a normal file or a directory using python?</p>
64
2009-06-05T13:47:31Z
955,955
<pre><code>import os if os.path.isdir(d): print "dir" else: print "file" </code></pre>
5
2009-06-05T13:51:01Z
[ "python" ]
How to identify whether a file is normal file or directory using python
955,941
<p>How do you check whether a file is a normal file or a directory using python?</p>
64
2009-06-05T13:47:31Z
955,956
<p><pre><code>os.path.isdir('string') os.path.isfile('string')</pre></code></p>
2
2009-06-05T13:51:32Z
[ "python" ]
How to identify whether a file is normal file or directory using python
955,941
<p>How do you check whether a file is a normal file or a directory using python?</p>
64
2009-06-05T13:47:31Z
955,957
<p>try this:</p> <pre><code>import os.path if os.path.isdir("path/to/your/file"): print "it's a directory" else: print "it's a file" </code></pre>
2
2009-06-05T13:51:39Z
[ "python" ]
How to identify whether a file is normal file or directory using python
955,941
<p>How do you check whether a file is a normal file or a directory using python?</p>
64
2009-06-05T13:47:31Z
956,092
<p>As other answers have said, <code>os.path.isdir()</code> and <code>os.path.isfile()</code> are what you want. However, you need to keep in mind that these are not the only two cases. Use <code>os.path.islink()</code> for symlinks for instance. Furthermore, these all return <code>False</code> if the file does not exist, so you'll probably want to check with <code>os.path.exists()</code> as well.</p>
27
2009-06-05T14:15:07Z
[ "python" ]
How to identify whether a file is normal file or directory using python
955,941
<p>How do you check whether a file is a normal file or a directory using python?</p>
64
2009-06-05T13:47:31Z
31,639,659
<p>If you're just stepping through a set of directories you might be better just to try <code>os.chdir</code> and give an error/warning if it fails:</p> <pre><code>import os,sys for DirName in sys.argv[1:]: SaveDir = os.getcwd() try: os.chdir(DirName) print "Changed to "+DirName # Do some stuff here in the directory os.chdir(SaveDir) except: sys.stderr.write("%s: WARNING: Cannot change to %s\n" % (sys.argv[0],DirName)) </code></pre>
0
2015-07-26T17:06:16Z
[ "python" ]
What is the correct way to set Python's locale on Windows?
955,986
<p>I'm attempting to sort a list of strings in a locale-aware manner. I've used the Babel library for other i18n-related tasks, but it doesn't support sorting. Python's <code>locale</code> module provides a <code>strcoll</code> function, but requires the locale of the process to be set to the one I want to work with. Kind of a pain, but I can live with it.</p> <p>The problem is that I can't seem to actually set the locale. The <a href="http://docs.python.org/library/locale.html">documentation</a> for the <code>locale</code> module gives this example:</p> <pre><code>import locale locale.setlocale(locale.LC_ALL, 'de_DE') </code></pre> <p>When I run that, I get this:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python26\Lib\locale.py", line 494, in setlocale locale.Error: unsupported locale setting </code></pre> <p>What am I doing wrong?</p>
50
2009-06-05T13:56:42Z
956,084
<p>It seems you're using Windows. The locale strings are different there. Take a more precise look at the doc:</p> <pre><code>locale.setlocale(locale.LC_ALL, 'de_DE') # use German locale; name might vary with platform </code></pre> <p>On Windows, I think it would be something like:</p> <pre><code>locale.setlocale(locale.LC_ALL, 'deu_deu') </code></pre> <p>MSDN has a list of <a href="http://msdn.microsoft.com/en-us/library/39cwe7zf%28vs.71%29.aspx">language strings</a> and of <a href="http://msdn.microsoft.com/en-us/library/cdax410z%28VS.71%29.aspx">country/region strings</a></p>
62
2009-06-05T14:13:18Z
[ "python", "localization", "internationalization" ]
What is the correct way to set Python's locale on Windows?
955,986
<p>I'm attempting to sort a list of strings in a locale-aware manner. I've used the Babel library for other i18n-related tasks, but it doesn't support sorting. Python's <code>locale</code> module provides a <code>strcoll</code> function, but requires the locale of the process to be set to the one I want to work with. Kind of a pain, but I can live with it.</p> <p>The problem is that I can't seem to actually set the locale. The <a href="http://docs.python.org/library/locale.html">documentation</a> for the <code>locale</code> module gives this example:</p> <pre><code>import locale locale.setlocale(locale.LC_ALL, 'de_DE') </code></pre> <p>When I run that, I get this:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python26\Lib\locale.py", line 494, in setlocale locale.Error: unsupported locale setting </code></pre> <p>What am I doing wrong?</p>
50
2009-06-05T13:56:42Z
1,395,480
<p>You should <strong>not pass an explicit locale</strong> to setlocale, it is wrong. Let it find out from the environment. You have to pass it an empty string</p> <pre><code>import locale locale.setlocale(locale.LC_ALL, '') </code></pre>
0
2009-09-08T18:19:35Z
[ "python", "localization", "internationalization" ]
What is the correct way to set Python's locale on Windows?
955,986
<p>I'm attempting to sort a list of strings in a locale-aware manner. I've used the Babel library for other i18n-related tasks, but it doesn't support sorting. Python's <code>locale</code> module provides a <code>strcoll</code> function, but requires the locale of the process to be set to the one I want to work with. Kind of a pain, but I can live with it.</p> <p>The problem is that I can't seem to actually set the locale. The <a href="http://docs.python.org/library/locale.html">documentation</a> for the <code>locale</code> module gives this example:</p> <pre><code>import locale locale.setlocale(locale.LC_ALL, 'de_DE') </code></pre> <p>When I run that, I get this:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python26\Lib\locale.py", line 494, in setlocale locale.Error: unsupported locale setting </code></pre> <p>What am I doing wrong?</p>
50
2009-06-05T13:56:42Z
20,939,063
<pre><code>def month_name(n): import datetime, locale locale.setlocale(locale.LC_ALL, '') return datetime.datetime.strptime(str(n), "%m").strftime("%B") </code></pre> <p>(tested in python 3 and 2.7.6)</p>
0
2014-01-05T20:56:13Z
[ "python", "localization", "internationalization" ]
What is the correct way to set Python's locale on Windows?
955,986
<p>I'm attempting to sort a list of strings in a locale-aware manner. I've used the Babel library for other i18n-related tasks, but it doesn't support sorting. Python's <code>locale</code> module provides a <code>strcoll</code> function, but requires the locale of the process to be set to the one I want to work with. Kind of a pain, but I can live with it.</p> <p>The problem is that I can't seem to actually set the locale. The <a href="http://docs.python.org/library/locale.html">documentation</a> for the <code>locale</code> module gives this example:</p> <pre><code>import locale locale.setlocale(locale.LC_ALL, 'de_DE') </code></pre> <p>When I run that, I get this:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python26\Lib\locale.py", line 494, in setlocale locale.Error: unsupported locale setting </code></pre> <p>What am I doing wrong?</p>
50
2009-06-05T13:56:42Z
23,304,594
<p>From locale.setlocale docs:</p> <pre><code>locale.setlocale(category, locale=None): """ Set the locale for the given category. The locale can be a string, an iterable of two strings (language code and encoding), or None. """" </code></pre> <p>Under Linux (especially Ubuntu) you can either use </p> <pre><code>locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8') </code></pre> <p>or</p> <pre><code>locale.setlocale(locale.LC_ALL, ('de', 'utf-8')) </code></pre> <p>You will get the same error if the locale is <strong>not installed</strong> on the system. So, make sure you have the locale <strong>installed</strong> on your system:</p> <pre><code>$ locale -a # to list the currently installed locales $ (sudo) locale-gen de_DE.UTF-8 # to install new locale </code></pre>
5
2014-04-25T23:16:46Z
[ "python", "localization", "internationalization" ]
What is the correct way to set Python's locale on Windows?
955,986
<p>I'm attempting to sort a list of strings in a locale-aware manner. I've used the Babel library for other i18n-related tasks, but it doesn't support sorting. Python's <code>locale</code> module provides a <code>strcoll</code> function, but requires the locale of the process to be set to the one I want to work with. Kind of a pain, but I can live with it.</p> <p>The problem is that I can't seem to actually set the locale. The <a href="http://docs.python.org/library/locale.html">documentation</a> for the <code>locale</code> module gives this example:</p> <pre><code>import locale locale.setlocale(locale.LC_ALL, 'de_DE') </code></pre> <p>When I run that, I get this:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python26\Lib\locale.py", line 494, in setlocale locale.Error: unsupported locale setting </code></pre> <p>What am I doing wrong?</p>
50
2009-06-05T13:56:42Z
24,485,432
<p>On Ubuntu you may have this problem because you don't have that local installed on your system.</p> <p>From shell try a:</p> <pre><code>$&gt; locale -a </code></pre> <p>and check if you find the locale you are interested in. Otherwise you have to install it:</p> <pre><code>$&gt; sudo apt-get install language-pack-XXX </code></pre> <p>where XXX is your language (in my case "xxx = it" , italian locale) Then run a dpkg-reconfigure:</p> <pre><code>$&gt; sudo dpkg-reconfigure locales </code></pre> <p>After that try again in your python shell:</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; locale.setlocale(locale.LC_ALL,'it_IT.UTF-8') </code></pre> <p>(this is for italian locale, which was what I needed)</p>
10
2014-06-30T07:59:59Z
[ "python", "localization", "internationalization" ]
Getting column info in cx_oracle when table is empty?
956,085
<p>I am working on an a handler for the python logging module. That essentially logs to an oracle database. </p> <p>I am using cx_oracle, and something i don't know how to get is the column values when the table is empty.</p> <pre><code>cursor.execute('select * from FOO') for row in cursor: # this is never executed because cursor has no rows print '%s\n' % row.description # This prints none row = cursor.fetchone() print str(row) row = cursor.fetchvars # prints useful info for each in row: print each </code></pre> <p>The output is:</p> <pre><code>None &lt;cx_Oracle.DATETIME with value [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None , None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None , None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]&gt; &lt;cx_Oracle.STRING with value [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]&gt; </code></pre> <p>Now looking at the var data i can see the data types, and their sizes (count nones?) but thats missing the column name.</p> <p>How can i go about this?</p>
6
2009-06-05T14:13:18Z
957,599
<p>I think the <a href="http://cx-oracle.readthedocs.org/en/latest/cursor.html#Cursor.description" rel="nofollow"><code>description</code></a> attribute may be what you are looking for. This returns a list of tuples that describe the columns of the data returned. It works quite happily if there are no rows returned, for example:</p> <pre> >>> import cx_Oracle >>> c = cx_Oracle.connect("username", "password") >>> cr = c.cursor() >>> cr.execute("select * from dual where 1=0") &lt;__builtin__.OracleCursor on &lt;cx_Oracle.Connection to user username@local&gt;&gt; >>> cr.description [('DUMMY', &lt;type 'cx_Oracle.STRING'&gt;, 1, 1, 0, 0, 1)] </pre>
12
2009-06-05T19:11:16Z
[ "python", "cx-oracle" ]
python: attributes on a generator object
956,585
<p>Is it possible to create an attribute on a generator object?</p> <p>Here's a very simple example:</p> <pre><code>def filter(x): for line in myContent: if line == x: yield x </code></pre> <p>Now say I have a lot of these filter generator objects floating around... maybe some of them are anonymous... I want to go back later and interrogate them for what they are filtering for. Is there a way I can a) interrogate the generator object for the value of x or b) set an attribute with the value of x that I can later interrogate?</p> <p>Thanks</p>
5
2009-06-05T15:39:54Z
956,600
<p>Yes.</p> <pre><code>class Filter( object ): def __init__( self, content ): self.content = content def __call__( self, someParam ): self.someParam = someParam for line in self.content: if line == someParam: yield line </code></pre>
13
2009-06-05T15:42:21Z
[ "python" ]
python: attributes on a generator object
956,585
<p>Is it possible to create an attribute on a generator object?</p> <p>Here's a very simple example:</p> <pre><code>def filter(x): for line in myContent: if line == x: yield x </code></pre> <p>Now say I have a lot of these filter generator objects floating around... maybe some of them are anonymous... I want to go back later and interrogate them for what they are filtering for. Is there a way I can a) interrogate the generator object for the value of x or b) set an attribute with the value of x that I can later interrogate?</p> <p>Thanks</p>
5
2009-06-05T15:39:54Z
956,634
<p>Unfortunately, generator objects (the results returned from calling a generator function) do not support adding arbitrary attributes. You can work around it to some extent by using an external dict indexed by the generator objects, since such objects <em>are</em> usable as keys into a dict. So where you'd <em>like</em> to do, say:</p> <pre><code>a = filter(23) b = filter(45) ... a.foo = 67 ... x = random.choice([a,b]) if hasattr(x, 'foo'): munge(x.foo) </code></pre> <p>you may instead do:</p> <pre><code>foos = dict() a = filter(23) b = filter(45) ... foos[a] = 67 ... x = random.choice([a,b]) if x in foos: munge(foos[x]) </code></pre> <p>For anything fancier, use a class instead of a generator (one or more of the class's methods can be generators, after all).</p>
6
2009-06-05T15:48:56Z
[ "python" ]
python: attributes on a generator object
956,585
<p>Is it possible to create an attribute on a generator object?</p> <p>Here's a very simple example:</p> <pre><code>def filter(x): for line in myContent: if line == x: yield x </code></pre> <p>Now say I have a lot of these filter generator objects floating around... maybe some of them are anonymous... I want to go back later and interrogate them for what they are filtering for. Is there a way I can a) interrogate the generator object for the value of x or b) set an attribute with the value of x that I can later interrogate?</p> <p>Thanks</p>
5
2009-06-05T15:39:54Z
956,667
<p>No. You can't set arbitrary attributes on generators.</p> <p>As S. Lott points out, you can have a object that <em>looks</em> like a generator, and <em>acts</em> like a generator. And if it looks like a duck, and acts like a duck, you've got yourself the very definition of duck typing, right there.</p> <p>It won't support generator attributes like <code>gi_frame</code> without the appropriate proxy methods, however.</p>
1
2009-06-05T15:55:20Z
[ "python" ]
python: attributes on a generator object
956,585
<p>Is it possible to create an attribute on a generator object?</p> <p>Here's a very simple example:</p> <pre><code>def filter(x): for line in myContent: if line == x: yield x </code></pre> <p>Now say I have a lot of these filter generator objects floating around... maybe some of them are anonymous... I want to go back later and interrogate them for what they are filtering for. Is there a way I can a) interrogate the generator object for the value of x or b) set an attribute with the value of x that I can later interrogate?</p> <p>Thanks</p>
5
2009-06-05T15:39:54Z
956,847
<p>Thinking about the problem, there <em>is</em> a way of having generators carry around a set of attributes. It's a little crazy--I'd strongly recommend Alex Martelli's suggestion instead of this--but it might be useful in some situations.</p> <pre><code>my_content = ['cat', 'dog days', 'catfish', 'dog', 'catalog'] def filter(x): _query = 'I\'m looking for %r' % x def _filter(): query = yield None for line in my_content: while query: query = yield _query if line.startswith(x): query = yield line while query: query = yield _query _f = _filter() _f.next() return _f for d in filter('dog'): print 'Found %s' % d cats = filter('cat') for c in cats: looking = cats.send(True) print 'Found %s (filter %r)' % (c, looking) </code></pre> <p>If you want to ask the generator what it's filtering on, just call <code>send</code> with a value that evaluates to true. Of course, this code is probably too clever by half. Use with caution.</p>
0
2009-06-05T16:28:48Z
[ "python" ]
python: attributes on a generator object
956,585
<p>Is it possible to create an attribute on a generator object?</p> <p>Here's a very simple example:</p> <pre><code>def filter(x): for line in myContent: if line == x: yield x </code></pre> <p>Now say I have a lot of these filter generator objects floating around... maybe some of them are anonymous... I want to go back later and interrogate them for what they are filtering for. Is there a way I can a) interrogate the generator object for the value of x or b) set an attribute with the value of x that I can later interrogate?</p> <p>Thanks</p>
5
2009-06-05T15:39:54Z
956,952
<p>If you want to interrogate them for debugging purposes, then the following function will help:</p> <pre><code>import inspect def inspect_generator(g): sourcecode = open(g.gi_code.co_filename).readlines() gline = g.gi_code.co_firstlineno generator_code = inspect.getblock(sourcecode[gline-1:]) output = "Generator %r from %r\n" % (g.gi_code.co_name, g.gi_code.co_filename) output += "".join("%4s: %s" % (idx+gline, line) for idx, line in enumerate(generator_code)) output += "Local variables:\n" output += "".join("%s = %r\n" % (key,value) for key,value in g.gi_frame.f_locals.items()) return output print inspect_generator(filter(6)) """Output: Generator 'filter' from 'generator_introspection.py' 1: def filter(x): 2: for line in myContent: 3: if line == x: 4: yield x Local variables: x = 6 """ </code></pre> <p>If you want to interrogate them to implement functionality then classes implementing the iterator protocol are probably a better idea.</p>
2
2009-06-05T16:53:07Z
[ "python" ]
python: attributes on a generator object
956,585
<p>Is it possible to create an attribute on a generator object?</p> <p>Here's a very simple example:</p> <pre><code>def filter(x): for line in myContent: if line == x: yield x </code></pre> <p>Now say I have a lot of these filter generator objects floating around... maybe some of them are anonymous... I want to go back later and interrogate them for what they are filtering for. Is there a way I can a) interrogate the generator object for the value of x or b) set an attribute with the value of x that I can later interrogate?</p> <p>Thanks</p>
5
2009-06-05T15:39:54Z
2,293,527
<p>I just wrote a decorator to do this here: <a href="http://code.activestate.com/recipes/577057-generator-attributes/" rel="nofollow">http://code.activestate.com/recipes/577057-generator-attributes/</a></p>
0
2010-02-19T01:32:30Z
[ "python" ]
python: attributes on a generator object
956,585
<p>Is it possible to create an attribute on a generator object?</p> <p>Here's a very simple example:</p> <pre><code>def filter(x): for line in myContent: if line == x: yield x </code></pre> <p>Now say I have a lot of these filter generator objects floating around... maybe some of them are anonymous... I want to go back later and interrogate them for what they are filtering for. Is there a way I can a) interrogate the generator object for the value of x or b) set an attribute with the value of x that I can later interrogate?</p> <p>Thanks</p>
5
2009-06-05T15:39:54Z
28,105,921
<p>I realize this is a very belated answer, but...</p> <p>Instead of storing and later reading some additional attribute, your code could later just inspect the generator's variable(s), using:</p> <p>filter.gi_frame.f_locals</p> <p>I guess Ants Aasma hinted at that.</p>
0
2015-01-23T08:37:45Z
[ "python" ]
Am I missing step in building/installing VTK-5.4 with Python2.6 bindings on Ubuntu 9.04?
956,716
<p>I successfully built and installed VTK-5.4 with Python bindings from source. Yet, when I try to import VTK in python it gives the following Traceback error</p> <blockquote> <p>File "", line 1, in </p> <p>File "/usr/local/lib/python2.6/dist-packages/VTK-5.4.2-py2.6.egg/vtk/<strong>init</strong>.py", line 41, in from common import * </p> <p>File "/usr/local/lib/python2.6/dist-packages/VTK-5.4.2-py2.6.egg/vtk/common.py", line 7, in from libvtkCommonPython import * </p> <p>ImportError: libvtkCommonPythonD.so.5.4: cannot open shared object file: No such file or directory</p> </blockquote> <p>So I am wondering what I am missing? I have tried adding /usr/local/lib/vtk-5.4 to both PATH and PYTHONPATH environment variables and still get the same result. Any hints or suggestions?</p> <p>NOTE: <em>libvtkCommonPythonD.so.5.4</em> exists in /usr/local/lib/vtk-5.4 as a symlink to <em>libvtkCommonPythonD.so.5.4.2</em></p>
3
2009-06-05T16:05:04Z
956,889
<p>Test if adding <code>/usr/local/lib</code> to your <code>$LD_LIBRARY_PATH</code> helps:</p> <p>In a shell:</p> <pre><code>export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib </code></pre> <p>If it works, make it permanent by (adding <code>/usr/local/lib</code> to <code>/etc/ld.so.conf</code>) _ (running '<code>ldconfig -n /usr/local/lib</code>')</p>
5
2009-06-05T16:36:42Z
[ "python", "3d", "vtk" ]
Python open raw audio data file
956,720
<p>I have these files with the extension ".adc". They are simply raw data files. I can open them with Audacity using File->Import->Raw data with encoding "Signed 16 bit" and sample rate "16000 Khz". </p> <p>I would like to do the same with python. I think that audioop module is what I need, but I can't seem to find examples on how to use it for something that simple.</p> <p>The main goal is to open the file and play a certain location in the file, for example from the second 10 to the second 20. Is there something out there for my task ?</p> <p>Thanx in advance.</p>
5
2009-06-05T16:05:51Z
956,755
<p>For opening the file, you just need <code>file()</code>. For finding a location, you don't need audioop: you just need to convert seconds to bytes and get the required bytes of the file. For instance, if your file is 16 kHz 16bit mono, each second is 32,000 bytes of data. So the 10th second is 320kB into the file. Just seek to the appropriate place in the file and then read the appropriate number of bytes.</p> <p>And audioop can't help you with the hardest part: namely, playing the audio. The correct way to do this very much depends on your OS.</p> <p>EDIT: Sorry, I just noticed your username is "thelinuxer". Consider <a href="http://nixbit.com/cat/programming/libraries/pyao/">pyAO</a> for playing audio from Python on Linux. You will probably need to change the sample format to play the audio---audioop will help you with this (see ratecv, tomono/tostereo, lin2lin, and bias)</p>
7
2009-06-05T16:10:57Z
[ "python", "audio" ]
Python open raw audio data file
956,720
<p>I have these files with the extension ".adc". They are simply raw data files. I can open them with Audacity using File->Import->Raw data with encoding "Signed 16 bit" and sample rate "16000 Khz". </p> <p>I would like to do the same with python. I think that audioop module is what I need, but I can't seem to find examples on how to use it for something that simple.</p> <p>The main goal is to open the file and play a certain location in the file, for example from the second 10 to the second 20. Is there something out there for my task ?</p> <p>Thanx in advance.</p>
5
2009-06-05T16:05:51Z
957,235
<p>Thanx a lot I was able to do the following:</p> <pre><code>def play_data(filename, first_sec, second_sec): import ao from ao import AudioDevice dev = AudioDevice(2, bits=16, rate=16000,channels=1) f = open(filename, 'r') data_len = (second_sec-first_sec)*32000 f.seek(32000*first_sec) data = f.read(data_len) dev.play(data) f.close() play_data('AR001_3.adc', 2.5, 5) </code></pre>
4
2009-06-05T17:58:49Z
[ "python", "audio" ]
Python open raw audio data file
956,720
<p>I have these files with the extension ".adc". They are simply raw data files. I can open them with Audacity using File->Import->Raw data with encoding "Signed 16 bit" and sample rate "16000 Khz". </p> <p>I would like to do the same with python. I think that audioop module is what I need, but I can't seem to find examples on how to use it for something that simple.</p> <p>The main goal is to open the file and play a certain location in the file, for example from the second 10 to the second 20. Is there something out there for my task ?</p> <p>Thanx in advance.</p>
5
2009-06-05T16:05:51Z
32,605,284
<p>You can use <a href="http://pysoundfile.readthedocs.org/" rel="nofollow">PySoundFile</a> to open the file as a NumPy array and play it with <a href="http://python-sounddevice.readthedocs.org/" rel="nofollow">python-sounddevice</a>.</p> <pre><code>import soundfile as sf import sounddevice as sd sig, fs = sf.read('myfile.adc', channels=2, samplerate=16000, format='RAW', subtype='PCM_16') sd.play(sig, fs) </code></pre> <p>You can use indexing on the NumPy array to select a certain part of the audio data.</p>
0
2015-09-16T09:54:01Z
[ "python", "audio" ]
Iterating through large lists with potential conditions in Python
956,820
<p>I have large chunks of data, normally at around 2000+ entries, but in this report we have the ability to look as far as we want so it could be up to 10,000 records</p> <p>The report is split up into: Two categories and then within each Category, we split by Currency so we have several sub categories within the list.</p> <p>My issue comes in efficiently calculating the various subtotals. I am using Django and pass a templatetag the currency and category, if it applies, and then the templatetag renders the total. Note that sometimes I have a subtotal just for the category, with no currency passed.</p> <p>Initially, I was using a seperate query for each subtotal by just using .filter() if there was a currency/category like so:</p> <pre><code>if currency: entries = entries.filter(item_currency=currency) </code></pre> <p>This became a problem as I would have too many queries, and too long of a generation time (2,000+ ms), so I opted to use list(entries) to execute my query right off the bat, and then loop through it with simple list comprehensions:</p> <pre><code>totals['quantity'] = sum([e.quantity for e in entries]) </code></pre> <p>My problem if you don't see it yet, lies in .. how can I efficiently add the condition for currency / category on each list comprehension? Sometimes they won't be there, sometimes they will so I can't simply type:</p> <pre><code>totals['quantity'] = sum([e.quantity for e in entries if item_currency = currency]) </code></pre> <p>I could make a huge if-block, but that's not very clean and is a maintenance disaster, so I'm reaching out to the Stackoverflow community for a bit of insight .. thanks in advance :)</p>
1
2009-06-05T16:24:17Z
956,852
<p>You could define a little inline function:</p> <pre><code>def EntryMatches(e): if use_currency and not (e.currency == currency): return False if use_category and not (e.category == category): return False return True </code></pre> <p>then</p> <pre><code>totals['quantity'] = sum([e.quantity for e in entries if EntryMatches(e)]) </code></pre> <p>EntryMatches() will have access to all variables in enclosing scope, so no need to pass in any more arguments. You get the advantage that all of the logic for which entries to use is in one place, you still get to use the list comprehension to make the sum() more readable, but you can have arbitrary logic in EntryMatches() now.</p>
6
2009-06-05T16:29:48Z
[ "python", "django", "list" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
956,927
<p>That's because json has no difference between string objects and unicode objects. They're all strings in javascript.</p> <p>I think <strong>JSON is right to return unicode objects</strong>. In fact, I wouldn't accept anything less, since javascript strings <strong>are in fact <code>unicode</code> objects</strong> (i.e. JSON (javascript) strings can store <em>any kind</em> of unicode character) so it makes sense to create <code>unicode</code> objects when translating strings from JSON. Plain strings just wouldn't fit since the library would have to guess the encoding you want.</p> <p>It's better to use <code>unicode</code> string objects everywhere. So your best option is to update your libraries so they can deal with unicode objects.</p> <p>But if you really want bytestrings, just encode the results to the encoding of your choice:</p> <pre><code>&gt;&gt;&gt; nl = json.loads(js) &gt;&gt;&gt; nl [u'a', u'b'] &gt;&gt;&gt; nl = [s.encode('utf-8') for s in nl] &gt;&gt;&gt; nl ['a', 'b'] </code></pre>
31
2009-06-05T16:44:45Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
957,274
<p>I'm afraid there's no way to achieve this automatically within the simplejson library.</p> <p>The scanner and decoder in simplejson are designed to produce unicode text. To do this, the library uses a function called <code>c_scanstring</code> (if it's available, for speed), or <code>py_scanstring</code> if the C version is not available. The <code>scanstring</code> function is called several times by nearly every routine that simplejson has for decoding a structure that might contain text. You'd have to either monkeypatch the <code>scanstring</code> value in simplejson.decoder, or subclass <code>JSONDecoder</code> and provide pretty much your own entire implementation of anything that might contain text.</p> <p>The reason that simplejson outputs unicode, however, is that the <a href="http://www.json.org/">json spec</a> specifically mentions that "A string is a collection of zero or more Unicode characters"... support for unicode is assumed as part of the format itself. Simplejson's <code>scanstring</code> implementation goes so far as to scan and interpret unicode escapes (even error-checking for malformed multi-byte charset representations), so the only way it can reliably return the value to you is as unicode.</p> <p>If you have an aged library that needs an <code>str</code>, I recommend you either laboriously search the nested data structure after parsing (which I acknowledge is what you explicitly said you wanted to avoid... sorry), or perhaps wrap your libraries in some sort of facade where you can massage the input parameters at a more granular level. The second approach might be more manageable than the first if your data structures are indeed deeply nested.</p>
9
2009-06-05T18:10:03Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
1,641,528
<p>This is late to the game, but I built this recursive caster. It works for my needs and I think it's relatively complete. It may help you.</p> <pre><code>def _parseJSON(self, obj): newobj = {} for key, value in obj.iteritems(): key = str(key) if isinstance(value, dict): newobj[key] = self._parseJSON(value) elif isinstance(value, list): if key not in newobj: newobj[key] = [] for i in value: newobj[key].append(self._parseJSON(i)) elif isinstance(value, unicode): val = str(value) if val.isdigit(): val = int(val) else: try: val = float(val) except ValueError: val = str(val) newobj[key] = val return newobj </code></pre> <p>Just pass it a JSON object like so:</p> <pre><code>obj = json.loads(content, parse_float=float, parse_int=int) obj = _parseJSON(obj) </code></pre> <p>I have it as a private member of a class, but you can repurpose the method as you see fit.</p>
0
2009-10-29T03:53:43Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
3,181,455
<p>So, I've run into the same problem. Guess what was the first Google result.</p> <p>Because I need to pass all data to PyGTK, unicode strings aren't very useful to me either. So I have another recursive conversion method. It's actually also needed for typesafe JSON conversion - json.dump() would bail on any non-literals, like Python objects. Doesn't convert dict indexes though.</p> <pre><code># removes any objects, turns unicode back into str def filter_data(obj): if type(obj) in (int, float, str, bool): return obj elif type(obj) == unicode: return str(obj) elif type(obj) in (list, tuple, set): obj = list(obj) for i,v in enumerate(obj): obj[i] = filter_data(v) elif type(obj) == dict: for i,v in obj.iteritems(): obj[i] = filter_data(v) else: print "invalid object in data, converting to string" obj = str(obj) return obj </code></pre>
1
2010-07-05T18:22:51Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
3,972,139
<p>The gotcha is that <code>simplejson</code> and <code>json</code> are two different modules, at least in the manner they deal with unicode. You have <code>json</code> in py 2.6+, and this gives you unicode values, whereas <code>simplejson</code> returns string objects. Just try easy_install-ing simplejson in your environment and see if that works. It did for me.</p>
3
2010-10-19T19:48:34Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
6,406,105
<p>I ran into this problem too, and having to deal with JSON, I came up with a small loop that converts the unicode keys to strings. (<code>simplejson</code> on GAE does not return string keys.)</p> <p><code>obj</code> is the object decoded from JSON:</p> <pre class="lang-py prettyprint-override"><code>if NAME_CLASS_MAP.has_key(cls): kwargs = {} for i in obj.keys(): kwargs[str(i)] = obj[i] o = NAME_CLASS_MAP[cls](**kwargs) o.save() </code></pre> <p><code>kwargs</code> is what I pass to the constructor of the GAE application (which does not like <code>unicode</code> keys in <code>**kwargs</code>)</p> <p>Not as robust as the solution from Wells, but much smaller.</p>
-1
2011-06-20T01:20:36Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
6,633,651
<p>You can use the <code>object_hook</code> parameter for <a href="http://docs.python.org/library/json.html#json.loads"><code>json.loads</code></a> to pass in a converter. You don't have to do the conversion after the fact. The <a href="http://docs.python.org/library/json.html"><code>json</code></a> module will always pass the <code>object_hook</code> dicts only, and it will recursively pass in nested dicts, so you don't have to recurse into nested dicts yourself. I don't think I would convert unicode strings to numbers like Wells shows. If it's a unicode string, it was quoted as a string in the JSON file, so it is supposed to be a string (or the file is bad).</p> <p>Also, I'd try to avoid doing something like <code>str(val)</code> on a <code>unicode</code> object. You should use <code>value.encode(encoding)</code> with a valid encoding, depending on what your external lib expects.</p> <p>So, for example:</p> <pre><code>def _decode_list(data): rv = [] for item in data: if isinstance(item, unicode): item = item.encode('utf-8') elif isinstance(item, list): item = _decode_list(item) elif isinstance(item, dict): item = _decode_dict(item) rv.append(item) return rv def _decode_dict(data): rv = {} for key, value in data.iteritems(): if isinstance(key, unicode): key = key.encode('utf-8') if isinstance(value, unicode): value = value.encode('utf-8') elif isinstance(value, list): value = _decode_list(value) elif isinstance(value, dict): value = _decode_dict(value) rv[key] = value return rv obj = json.loads(s, object_hook=_decode_dict) </code></pre>
68
2011-07-09T08:25:41Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
13,105,359
<p>There's no built-in option to make the json module functions return byte strings instead of unicode strings. However, this short and simple recursive function will convert any decoded JSON object from using unicode strings to UTF-8-encoded byte strings:</p> <pre><code>def byteify(input): if isinstance(input, dict): return {byteify(key): byteify(value) for key, value in input.iteritems()} elif isinstance(input, list): return [byteify(element) for element in input] elif isinstance(input, unicode): return input.encode('utf-8') else: return input </code></pre> <p>Just call this on the output you get from a <code>json.load</code> or <code>json.loads</code> call.</p> <p>A couple of notes:</p> <ul> <li>To support Python 2.6 or earlier, replace <code>return {byteify(key): byteify(value) for key, value in input.iteritems()}</code> with <code>return dict([(byteify(key), byteify(value)) for key, value in input.iteritems()])</code>, since dictionary comprehensions weren't supported until Python 2.7.</li> <li>Since this answer recurses through the entire decoded object, it has a couple of undesirable performance characteristics that can be avoided with very careful use of the <code>object_hook</code> or <code>object_pairs_hook</code> parameters. <a href="http://stackoverflow.com/a/33571117/1709587">Mirec Miskuf's answer</a> is so far the only one that manages to pull this off correctly, although as a consequence, it's significantly more complicated than my approach.</li> </ul>
112
2012-10-28T00:27:17Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
16,373,377
<p>While there are some good answers here, I ended up using <a href="http://pyyaml.org/">PyYAML</a> to parse my JSON files, since it gives the keys and values as <code>str</code> type strings instead of <code>unicode</code> type. Because JSON is a subset of YAML it works nicely:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; import yaml &gt;&gt;&gt; list_org = ['a', 'b'] &gt;&gt;&gt; list_dump = json.dumps(list_org) &gt;&gt;&gt; list_dump '["a", "b"]' &gt;&gt;&gt; json.loads(list_dump) [u'a', u'b'] &gt;&gt;&gt; yaml.safe_load(list_dump) ['a', 'b'] </code></pre> <p>Some things to note though:</p> <ul> <li><p>I get <em>string objects</em> because all my entries are <strong>ASCII encoded</strong>. If I would use unicode encoded entries, I would get them back as <em>unicode objects</em> — there is no conversion!</p></li> <li><p>You should (probably always) use PyYAML's <code>safe_load</code> function; if you use it to load JSON files, you don't need the "additional power" of the <code>load</code> function anyway.</p></li> <li><p>If you want a YAML parser that has more support for the 1.2 version of the spec (and <a href="http://stackoverflow.com/questions/30458977/yaml-loads-5e-6-as-string-and-not-a-number">correctly parses very low numbers</a>) try <a href="https://bitbucket.org/ruamel/yaml">Ruamel YAML</a>: <code>pip install ruamel.yaml</code> and <code>import ruamel.yaml as yaml</code> was all I needed in my tests.</p></li> </ul> <p>As stated, there is no conversion! If you can't be sure to only deal with ASCII values (and you can't be sure most of the time), better use a <strong>conversion function</strong>:</p> <p>I used the one from <a href="http://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-ones-from-json-in-python/13105359#13105359">Mark Amery</a> a couple of times now, it works great and is very easy to use. You can also use a similar function as an <code>object_hook</code> instead, as it might gain you a performance boost on big files. See the slightly more involved <a href="http://stackoverflow.com/a/33571117/11666">answer from Mirec Miskuf</a> for that.</p>
121
2013-05-04T10:37:24Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
16,976,651
<p>I rewrote Wells's _parse_json() to handle cases where the json object itself is an array (my use case).</p> <pre><code>def _parseJSON(self, obj): if isinstance(obj, dict): newobj = {} for key, value in obj.iteritems(): key = str(key) newobj[key] = self._parseJSON(value) elif isinstance(obj, list): newobj = [] for value in obj: newobj.append(self._parseJSON(value)) elif isinstance(obj, unicode): newobj = str(obj) else: newobj = obj return newobj </code></pre>
0
2013-06-07T05:12:22Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
19,826,039
<p>There exists an easy work-around.</p> <p>TL;DR - Use <code>ast.literal_eval()</code> instead of <code>json.loads()</code>. Both <code>ast</code> and <code>json</code> are in the standard library.</p> <p>While not a 'perfect' answer, it gets one pretty far if your plan is to ignore Unicode altogether. In Python 2.7</p> <pre><code>import json, ast d = { 'field' : 'value' } print "JSON Fail: ", json.loads(json.dumps(d)) print "AST Win:", ast.literal_eval(json.dumps(d)) </code></pre> <p>gives:</p> <pre><code>JSON Fail: {u'field': u'value'} AST Win: {'field': 'value'} </code></pre> <p>This gets more hairy when some objects are really Unicode strings. The full answer gets hairy quickly.</p>
11
2013-11-07T01:01:43Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
23,328,454
<p>Just use pickle instead of json for dump and load, like so:</p> <pre><code> import json import pickle d = { 'field1': 'value1', 'field2': 2, } json.dump(d,open("testjson.txt","w")) print json.load(open("testjson.txt","r")) pickle.dump(d,open("testpickle.txt","w")) print pickle.load(open("testpickle.txt","r")) </code></pre> <p>The output it produces is (strings and integers are handled correctly):</p> <pre><code> {u'field2': 2, u'field1': u'value1'} {'field2': 2, 'field1': 'value1'} </code></pre>
0
2014-04-27T20:15:01Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
28,233,545
<p>I had a json dict as a string. The keys and values where unicode objects like in the following example:</p> <p>myStringDict = "{u'key':u'value'}"</p> <p>I could use the byteify function suggested above by previously converting the string to a dict object using ast.literal_eval(myStringDict).</p>
-1
2015-01-30T10:12:14Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
29,633,899
<p>As Mark (Amery) correctly notes: Using <strong>PyYaml</strong>'s deserializer on a json dump works only if you have ASCII only. At least out of the box. </p> <p>Two quick comments on the PyYaml approach:</p> <ol> <li><p><a href="https://t.co/BaFO5CPyIF">NEVER</a> use yaml.load on data from the field. Its a feature(!) of yaml to execute arbitrary code hidden within the structure. </p></li> <li><p>You <em>can</em> make it work also for non ASCII via this:</p> <pre><code>def to_utf8(loader, node): return loader.construct_scalar(node).encode('utf-8') yaml.add_constructor(u'tag:yaml.org,2002:str', to_utf8) </code></pre></li> </ol> <p>But performance wise its of no comparison to Mark Amery's answer:</p> <p>Throwing some deeply nested sample dicts onto the two methods, I get this (with dt[j] = time delta of json.loads(json.dumps(m))):</p> <pre><code> dt[yaml.safe_load(json.dumps(m))] =~ 100 * dt[j] dt[byteify recursion(Mark Amery)] =~ 5 * dt[j] </code></pre> <p>So deserialization including fully walking the tree <em>and</em> encoding, well within the order of magnitude of json's C based implementation. I find this remarkably fast and its also more robust than the yaml load at deeply nested structures. And less security error prone, looking at yaml.load.</p> <p>=> While I would appreciate a pointer to a C only based converter the <strong>byteify function</strong> should be the default answer. </p> <p>This holds especially true if your json structure is from the field, containing user input. Because then you probably need to walk <em>anyway</em> over your structure - independent on your desired internal data structures ('unicode sandwich' or byte strings only).</p> <p>Why?</p> <p>Unicode <strong>normalisation</strong>. For the unaware: Take a painkiller and read <a href="https://dev.twitter.com/overview/api/counting-characters" rel="nofollow">this</a>.</p> <p>So using the byteify recursion you kill two birds with one stone: </p> <ol> <li>get your bytestrings from nested json dumps</li> <li>get user input values normalised, so that you find the stuff in your storage.</li> </ol> <p>In my tests it turned out that replacing the input.encode('utf-8') with a unicodedata.normalize('NFC', input).encode('utf-8') was even faster than w/o NFC - but thats heavily dependent on the sample data I guess.</p>
3
2015-04-14T17:36:25Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
30,030,529
<p>here is a recursive encoder written in C: <a href="https://github.com/axiros/nested_encode" rel="nofollow">https://github.com/axiros/nested_encode</a></p> <p>Performance overhead for "average" structures around 10% compared to json.loads.</p> <pre><code>python speed.py json loads [0.16sec]: {u'a': [{u'b': [[1, 2, [u'\xd6ster.. json loads + encoding [0.18sec]: {'a': [{'b': [[1, 2, ['\xc3\x96ster. time overhead in percent: 9% </code></pre> <p>using this teststructure:</p> <pre><code>import json, nested_encode, time s = """ { "firstName": "Jos\\u0301", "lastName": "Smith", "isAlive": true, "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "\\u00d6sterreich", "state": "NY", "postalCode": "10021-3100" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "office", "number": "646 555-4567" } ], "children": [], "spouse": null, "a": [{"b": [[1, 2, ["\\u00d6sterreich"]]]}] } """ t1 = time.time() for i in xrange(10000): u = json.loads(s) dt_json = time.time() - t1 t1 = time.time() for i in xrange(10000): b = nested_encode.encode_nested(json.loads(s)) dt_json_enc = time.time() - t1 print "json loads [%.2fsec]: %s..." % (dt_json, str(u)[:20]) print "json loads + encoding [%.2fsec]: %s..." % (dt_json_enc, str(b)[:20]) print "time overhead in percent: %i%%" % (100 * (dt_json_enc - dt_json)/dt_json) </code></pre>
0
2015-05-04T12:44:46Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
31,005,819
<p>I've adapted the code from the <a href="https://stackoverflow.com/a/13105359/611007">answer</a> of <a href="https://stackoverflow.com/users/1709587/mark-amery">Mark Amery</a>, particularly in order to get rid of <code>isinstance</code> for the pros of duck-typing.</p> <p>The encoding is done manually and <code>ensure_ascii</code> is disabled. The python docs for <a href="https://docs.python.org/2/library/json.html#json.dump" rel="nofollow"><code>json.dump</code></a> says that </p> <blockquote> <p>If ensure_ascii is True (the default), all non-ASCII characters in the output are escaped with \uXXXX sequences</p> </blockquote> <p>Disclaimer: in the doctest I used the Hungarian language. Some notable Hungarian-related character encodings are: <code>cp852</code> the IBM/OEM encoding used eg. in DOS (sometimes referred as <em>ascii</em>, incorrectly I think, it is dependent on the <em>codepage</em> setting), <code>cp1250</code> used eg. in Windows (sometimes referred as <em>ansi</em>, dependent on the locale settings), and <code>iso-8859-2</code>, sometimes used on http servers. The test text <code>Tüskéshátú kígyóbűvölő</code> is attributed to <em>Koltai László</em> (native personal name form) and is from <a href="https://hu.wikipedia.org/wiki/%C3%81rv%C3%ADzt%C5%B1r%C5%91_t%C3%BCk%C3%B6rf%C3%BAr%C3%B3g%C3%A9p#Egy.C3.A9b_magyar_tesztsz.C3.B6vegek" rel="nofollow">wikipedia</a>.</p> <pre><code># coding: utf-8 """ This file should be encoded correctly with utf-8. """ import json def encode_items(input, encoding='utf-8'): u"""original from: https://stackoverflow.com/a/13101776/611007 adapted by SO/u/611007 (20150623) &gt;&gt;&gt; &gt;&gt;&gt; ## run this with `python -m doctest &lt;this file&gt;.py` from command line &gt;&gt;&gt; &gt;&gt;&gt; txt = u"Tüskéshátú kígyóbűvölő" &gt;&gt;&gt; txt2 = u"T\\u00fcsk\\u00e9sh\\u00e1t\\u00fa k\\u00edgy\\u00f3b\\u0171v\\u00f6l\\u0151" &gt;&gt;&gt; txt3 = u"uúuutifu" &gt;&gt;&gt; txt4 = b'u\\xfauutifu' &gt;&gt;&gt; # txt4 shouldn't be 'u\\xc3\\xbauutifu', string content needs double backslash for doctest: &gt;&gt;&gt; assert u'\\u0102' not in b'u\\xfauutifu'.decode('cp1250') &gt;&gt;&gt; txt4u = txt4.decode('cp1250') &gt;&gt;&gt; assert txt4u == u'u\\xfauutifu', repr(txt4u) &gt;&gt;&gt; txt5 = b"u\\xc3\\xbauutifu" &gt;&gt;&gt; txt5u = txt5.decode('utf-8') &gt;&gt;&gt; txt6 = u"u\\u251c\\u2551uutifu" &gt;&gt;&gt; there_and_back_again = lambda t: encode_items(t, encoding='utf-8').decode('utf-8') &gt;&gt;&gt; assert txt == there_and_back_again(txt) &gt;&gt;&gt; assert txt == there_and_back_again(txt2) &gt;&gt;&gt; assert txt3 == there_and_back_again(txt3) &gt;&gt;&gt; assert txt3.encode('cp852') == there_and_back_again(txt4u).encode('cp852') &gt;&gt;&gt; assert txt3 == txt4u,(txt3,txt4u) &gt;&gt;&gt; assert txt3 == there_and_back_again(txt5) &gt;&gt;&gt; assert txt3 == there_and_back_again(txt5u) &gt;&gt;&gt; assert txt3 == there_and_back_again(txt4u) &gt;&gt;&gt; assert txt3.encode('cp1250') == encode_items(txt4, encoding='utf-8') &gt;&gt;&gt; assert txt3.encode('utf-8') == encode_items(txt5, encoding='utf-8') &gt;&gt;&gt; assert txt2.encode('utf-8') == encode_items(txt, encoding='utf-8') &gt;&gt;&gt; assert {'a':txt2.encode('utf-8')} == encode_items({'a':txt}, encoding='utf-8') &gt;&gt;&gt; assert [txt2.encode('utf-8')] == encode_items([txt], encoding='utf-8') &gt;&gt;&gt; assert [[txt2.encode('utf-8')]] == encode_items([[txt]], encoding='utf-8') &gt;&gt;&gt; assert [{'a':txt2.encode('utf-8')}] == encode_items([{'a':txt}], encoding='utf-8') &gt;&gt;&gt; assert {'b':{'a':txt2.encode('utf-8')}} == encode_items({'b':{'a':txt}}, encoding='utf-8') """ try: input.iteritems return {encode_items(k): encode_items(v) for (k,v) in input.iteritems()} except AttributeError: if isinstance(input, unicode): return input.encode(encoding) elif isinstance(input, str): return input try: iter(input) return [encode_items(e) for e in input] except TypeError: return input def alt_dumps(obj, **kwargs): """ &gt;&gt;&gt; alt_dumps({'a': u"T\\u00fcsk\\u00e9sh\\u00e1t\\u00fa k\\u00edgy\\u00f3b\\u0171v\\u00f6l\\u0151"}) '{"a": "T\\xc3\\xbcsk\\xc3\\xa9sh\\xc3\\xa1t\\xc3\\xba k\\xc3\\xadgy\\xc3\\xb3b\\xc5\\xb1v\\xc3\\xb6l\\xc5\\x91"}' """ if 'ensure_ascii' in kwargs: del kwargs['ensure_ascii'] return json.dumps(encode_items(obj), ensure_ascii=False, **kwargs) </code></pre> <p>I'd also like to highlight the <a href="https://stackoverflow.com/a/957274/611007">answer</a> of <a href="https://stackoverflow.com/users/72247/jarret-hardie">Jarret Hardie</a> which references the <a href="https://www.json.org/" rel="nofollow">JSON spec</a>, quoting:</p> <blockquote> <p>A string is a collection of zero or more Unicode characters</p> </blockquote> <p>In my use-case I had files with json. They are <code>utf-8</code> encoded files. <code>ensure_ascii</code> results in properly escaped but not very readable json files, that is why I've adapted Mark Amery's answer to fit my needs.</p> <p>The doctest is not particularly thoughtful but I share the code in the hope that it will useful for someone.</p>
-1
2015-06-23T14:36:54Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
33,571,117
<h3>A solution with <code>object_hook</code></h3> <pre><code>import json def json_load_byteified(file_handle): return _byteify( json.load(file_handle, object_hook=_byteify), ignore_dicts=True ) def json_loads_byteified(json_text): return _byteify( json.loads(json_text, object_hook=_byteify), ignore_dicts=True ) def _byteify(data, ignore_dicts = False): # if this is a unicode string, return its string representation if isinstance(data, unicode): return data.encode('utf-8') # if this is a list of values, return list of byteified values if isinstance(data, list): return [ _byteify(item, ignore_dicts=True) for item in data ] # if this is a dictionary, return dictionary of byteified keys and values # but only if we haven't already byteified it if isinstance(data, dict) and not ignore_dicts: return { _byteify(key, ignore_dicts=True): _byteify(value, ignore_dicts=True) for key, value in data.iteritems() } # if it's anything else, return it in its original form return data </code></pre> <p>Example usage:</p> <pre><code>>>> <b><i>json_loads_byteified('{"Hello": "World"}')</i></b> {'Hello': 'World'} >>> <b><i>json_loads_byteified('"I am a top-level string"')</i></b> 'I am a top-level string' >>> <b><i>json_loads_byteified('7')</i></b> 7 >>> <b><i>json_loads_byteified('["I am inside a list"]')</i></b> ['I am inside a list'] >>> <b><i>json_loads_byteified('[[[[[[[["I am inside a big nest of lists"]]]]]]]]')</i></b> [[[[[[[['I am inside a big nest of lists']]]]]]]] >>> <b><i>json_loads_byteified('{"foo": "bar", "things": [7, {"qux": "baz", "moo": {"cow": ["milk"]}}]}')</i></b> {'things': [7, {'qux': 'baz', 'moo': {'cow': ['milk']}}], 'foo': 'bar'} >>> <b><i>json_load_byteified(open('somefile.json'))</i></b> {'more json': 'from a file'}</code></pre> <h3>How does this work and why would I use it?</h3> <p><a href="http://stackoverflow.com/a/13105359/1709587">Mark Amery's function</a> is shorter and clearer than these ones, so what's the point of them? Why would you want to use them?</p> <p>Purely for <strong>performance</strong>. Mark's answer decodes the JSON text fully first with unicode strings, then recurses through the entire decoded value to convert all strings to byte strings. This has a couple of undesirable effects:</p> <ul> <li>A copy of the entire decoded structure gets created in memory</li> <li>If your JSON object is <em>really</em> deeply nested (500 levels or more) then you'll hit Python's maximum recursion depth</li> </ul> <p>This answer mitigates both of those performance issues by using the <code>object_hook</code> parameter of <code>json.load</code> and <code>json.loads</code>. From <a href="https://docs.python.org/2/library/json.html#json.load">the docs</a>:</p> <blockquote> <p><code>object_hook</code> is an optional function that will be called with the result of any object literal decoded (a <code>dict</code>). The return value of object_hook will be used instead of the <code>dict</code>. This feature can be used to implement custom decoders</p> </blockquote> <p>Since dictionaries nested many levels deep in other dictionaries get passed to <code>object_hook</code> <em>as they're decoded</em>, we can byteify any strings or lists inside them at that point and avoid the need for deep recursion later.</p> <p>Mark's answer isn't suitable for use as an <code>object_hook</code> as it stands, because it recurses into nested dictionaries. We prevent that recursion in this answer with the <code>ignore_dicts</code> parameter to <code>_byteify</code>, which gets passed to it at all times <em>except</em> when <code>object_hook</code> passes it a new <code>dict</code> to byteify. The <code>ignore_dicts</code> flag tells <code>_byteify</code> to ignore <code>dict</code>s since they already been byteified.</p> <p>Finally, our implementations of <code>json_load_byteified</code> and <code>json_loads_byteified</code> call <code>_byteify</code> (with <code>ignore_dicts=True</code>) on the result returned from <code>json.load</code> or <code>json.loads</code> to handle the case where the JSON text being decoded doesn't have a <code>dict</code> at the top level.</p>
23
2015-11-06T16:18:59Z
[ "python", "json", "serialization", "unicode", "yaml" ]
How to get string objects instead of Unicode ones from JSON in Python?
956,867
<p>I'm using <strong>Python 2</strong> to parse JSON from (<strong>ASCII encoded</strong>) text files. When loading these files with either <a href="https://docs.python.org/2/library/json.html"><code>json</code></a> or <a href="https://pypi.python.org/pypi/simplejson/"><code>simplejson</code></a>, all my string values are cast to Unicode objects instead of string objects.</p> <p>The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.</p> <p>Is it possible to get string objects instead of Unicode ones from <code>json</code> or <code>simplejson</code>?</p> <p>Here's a small example:</p> <pre><code>>>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`</code></pre>
176
2009-06-05T16:32:17Z
34,796,078
<p><a href="http://stackoverflow.com/a/6633651/1517753">Mike Brennan's answer</a> is close, but there is no reason to re-traverse the entire structure. If you use the <a href="https://docs.python.org/2/library/json.html#json.load" rel="nofollow"><code>object_hook_pairs</code></a> (Python 2.7+) parameter:</p> <blockquote> <p><em><code>object_pairs_hook</code></em> is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of <em><code>object_pairs_hook</code></em> will be used instead of the <code>dict</code>. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, <code>collections.OrderedDict</code> will remember the order of insertion). If <em><code>object_hook</code></em> is also defined, the <em><code>object_pairs_hook</code></em> takes priority.</p> </blockquote> <p>With it, you get each JSON object handed to you, so you can do the decoding with no need for recursion:</p> <pre><code>def deunicodify_hook(pairs): new_pairs = [] for key, value in pairs: if isinstance(value, unicode): value = value.encode('utf-8') if isinstance(key, unicode): key = key.encode('utf-8') new_pairs.append((key, value)) return dict(new_pairs) In [52]: open('test.json').read() Out[52]: '{"1": "hello", "abc": [1, 2, 3], "def": {"hi": "mom"}, "boo": [1, "hi", "moo", {"5": "some"}]}' In [53]: json.load(open('test.json')) Out[53]: {u'1': u'hello', u'abc': [1, 2, 3], u'boo': [1, u'hi', u'moo', {u'5': u'some'}], u'def': {u'hi': u'mom'}} In [54]: json.load(open('test.json'), object_pairs_hook=deunicodify_hook) Out[54]: {'1': 'hello', 'abc': [1, 2, 3], 'boo': [1, 'hi', 'moo', {'5': 'some'}], 'def': {'hi': 'mom'}} </code></pre> <p>Notice that I never have to call the hook recursively since every object will get handed to the hook when you use the <code>object_pairs_hook</code>. You do have to care about lists, but as you can see, an object within a list will be properly converted, and you don't have to recurse to make it happen.</p> <p>EDIT: A coworker pointed out that Python2.6 doesn't have <code>object_hook_pairs</code>. You can still use this will Python2.6 by making a very small change. In the hook above, change:</p> <pre><code>for key, value in pairs: </code></pre> <p>to</p> <pre><code>for key, value in pairs.iteritems(): </code></pre> <p>Then use <code>object_hook</code> instead of <code>object_pairs_hook</code>:</p> <pre><code>In [66]: json.load(open('test.json'), object_hook=deunicodify_hook) Out[66]: {'1': 'hello', 'abc': [1, 2, 3], 'boo': [1, 'hi', 'moo', {'5': 'some'}], 'def': {'hi': 'mom'}} </code></pre> <p>Using <code>object_pairs_hook</code> results in one less dictionary being instantiated for each object in the JSON object, which, if you were parsing a huge document, might be worth while.</p>
5
2016-01-14T17:34:06Z
[ "python", "json", "serialization", "unicode", "yaml" ]
mounting an s3 bucket in ec2 and using transparently as a mnt point
956,904
<p>I have a webapp (call it myapp.com) that allows users to upload files. The webapp will be deployed on Amazon EC2 instance. I would like to serve these files back out to the webapp consumers via an s3 bucket based domain (i.e. uploads.myapp.com). </p> <p>When the user uploads the files, I can easily drop them in into a folder called "site_uploads" on the local ec2 instance. However, since my ec2 instance has finite storage, with a lot of uploads, the ec2 file system will fill up quickly. </p> <p>It would be great if the ec2 instance could mount and s3 bucket as the "site_upload" directory. So that uploads to the EC2 "site_upload" directory <em>automatically</em> end up on uploads.myapp.com (and my webapp can use template tags to make sure the links for this uploaded content is based on that s3 backed domain). This also gives me scalable file serving, as request for files hits s3 and not my ec2 instance. Also, it makes it easy for my webapp to perform scaling/resizing of the images that appear locally in "site_upload" but are actually on s3.</p> <p>I'm looking at s3fs, but judging from the comments, it doesn't look like a fully baked solution. I'm looking for a non-commercial solution.</p> <p>FYI, The webapp is written in django, not that that changes the particulars too much. </p>
4
2009-06-05T16:39:25Z
957,033
<p>For uploads, your users can <a href="http://stackoverflow.com/questions/117810/upload-files-directly-to-amazon-s3-from-asp-net-application">upload directly to S3</a>, as described <a href="http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?UsingHTTPPOST.html" rel="nofollow">here</a>.</p> <p>This way you won't need to mount S3.</p> <p>When serving the files, you can also do that from S3 directly by marking the files public, I'd prefer to name the site "files.mydomain.com" or "images.mydomain.com" pointing to s3.</p>
2
2009-06-05T17:12:12Z
[ "python", "django", "amazon-s3", "amazon-ec2" ]
mounting an s3 bucket in ec2 and using transparently as a mnt point
956,904
<p>I have a webapp (call it myapp.com) that allows users to upload files. The webapp will be deployed on Amazon EC2 instance. I would like to serve these files back out to the webapp consumers via an s3 bucket based domain (i.e. uploads.myapp.com). </p> <p>When the user uploads the files, I can easily drop them in into a folder called "site_uploads" on the local ec2 instance. However, since my ec2 instance has finite storage, with a lot of uploads, the ec2 file system will fill up quickly. </p> <p>It would be great if the ec2 instance could mount and s3 bucket as the "site_upload" directory. So that uploads to the EC2 "site_upload" directory <em>automatically</em> end up on uploads.myapp.com (and my webapp can use template tags to make sure the links for this uploaded content is based on that s3 backed domain). This also gives me scalable file serving, as request for files hits s3 and not my ec2 instance. Also, it makes it easy for my webapp to perform scaling/resizing of the images that appear locally in "site_upload" but are actually on s3.</p> <p>I'm looking at s3fs, but judging from the comments, it doesn't look like a fully baked solution. I'm looking for a non-commercial solution.</p> <p>FYI, The webapp is written in django, not that that changes the particulars too much. </p>
4
2009-06-05T16:39:25Z
983,308
<p>I'm not using EC2, but I do have my S3 bucket permanently mounted on my Linux server. The way I did it is with Jungledisk. It isn't a non-commercial solution, but it's very inexpensive.</p> <p>First I setup the jungledisk as normal. Then I make sure fuse is installed. Mostly you just need to create the configuration file with your secret keys and such. Then just add a line to your fstab something like this.</p> <pre><code>jungledisk /path/to/mount/at fuse noauto,allow_other,config=/path/to/jungledisk/config/file.xml 0 0 </code></pre> <p>Then just mount, and you're good to go.</p>
5
2009-06-11T20:02:10Z
[ "python", "django", "amazon-s3", "amazon-ec2" ]
mounting an s3 bucket in ec2 and using transparently as a mnt point
956,904
<p>I have a webapp (call it myapp.com) that allows users to upload files. The webapp will be deployed on Amazon EC2 instance. I would like to serve these files back out to the webapp consumers via an s3 bucket based domain (i.e. uploads.myapp.com). </p> <p>When the user uploads the files, I can easily drop them in into a folder called "site_uploads" on the local ec2 instance. However, since my ec2 instance has finite storage, with a lot of uploads, the ec2 file system will fill up quickly. </p> <p>It would be great if the ec2 instance could mount and s3 bucket as the "site_upload" directory. So that uploads to the EC2 "site_upload" directory <em>automatically</em> end up on uploads.myapp.com (and my webapp can use template tags to make sure the links for this uploaded content is based on that s3 backed domain). This also gives me scalable file serving, as request for files hits s3 and not my ec2 instance. Also, it makes it easy for my webapp to perform scaling/resizing of the images that appear locally in "site_upload" but are actually on s3.</p> <p>I'm looking at s3fs, but judging from the comments, it doesn't look like a fully baked solution. I'm looking for a non-commercial solution.</p> <p>FYI, The webapp is written in django, not that that changes the particulars too much. </p>
4
2009-06-05T16:39:25Z
989,280
<p>I use s3fs, but there are no readily available distributions. I've got my build here for anyone who wants it easier.</p> <p>Configuration documentation wasn't available, so I winged it until I got this in my fstab:</p> <p>s3fs#{{ bucket name }} {{ /path/to/mount/point }} fuse allow_other,accessKeyId={{ key }},secretAccessKey={{ secret key }} 0 0</p> <p><a href="http://drop.io/ironfroggy/asset/s3fs" rel="nofollow">s3fs</a></p>
2
2009-06-12T22:07:01Z
[ "python", "django", "amazon-s3", "amazon-ec2" ]
mounting an s3 bucket in ec2 and using transparently as a mnt point
956,904
<p>I have a webapp (call it myapp.com) that allows users to upload files. The webapp will be deployed on Amazon EC2 instance. I would like to serve these files back out to the webapp consumers via an s3 bucket based domain (i.e. uploads.myapp.com). </p> <p>When the user uploads the files, I can easily drop them in into a folder called "site_uploads" on the local ec2 instance. However, since my ec2 instance has finite storage, with a lot of uploads, the ec2 file system will fill up quickly. </p> <p>It would be great if the ec2 instance could mount and s3 bucket as the "site_upload" directory. So that uploads to the EC2 "site_upload" directory <em>automatically</em> end up on uploads.myapp.com (and my webapp can use template tags to make sure the links for this uploaded content is based on that s3 backed domain). This also gives me scalable file serving, as request for files hits s3 and not my ec2 instance. Also, it makes it easy for my webapp to perform scaling/resizing of the images that appear locally in "site_upload" but are actually on s3.</p> <p>I'm looking at s3fs, but judging from the comments, it doesn't look like a fully baked solution. I'm looking for a non-commercial solution.</p> <p>FYI, The webapp is written in django, not that that changes the particulars too much. </p>
4
2009-06-05T16:39:25Z
4,327,061
<p>This is a little snipped that I use for an Ubuntu system and I have not tested it on so it will obviously need to be adapted for a M$ system. You'll also need to install <a href="http://code.google.com/p/s3-simple-fuse/" rel="nofollow">s3-simple-fuse</a>. If you wind up eventually putting your job to the clound, I'd recommend fabric to run the same command.</p> <pre><code>import os, subprocess ''' Note: this is for Linux with s3cmd installed and libfuse2 installed Run: 'fusermount -u mount_directory' to unmount ''' def mountS3(aws_access_key_id, aws_secret_access_key, targetDir, bucketName = None): ####### if bucketName is None: bucketName = 's3Bucket' mountDir = os.path.join(targetDir, bucketName) if not os.path.isdir(mountDir): os.path.mkdir(mountDir) subprocess.call('s3-simple-fuse %s -o AWS_ACCESS_KEY_ID=%s,AWS_SECRET_ACCESS_KEY=%s,bucket=%s'%(mountDir, aws_access_key_id, aws_secret_access_key, bucketName) </code></pre>
2
2010-12-01T17:19:38Z
[ "python", "django", "amazon-s3", "amazon-ec2" ]
mounting an s3 bucket in ec2 and using transparently as a mnt point
956,904
<p>I have a webapp (call it myapp.com) that allows users to upload files. The webapp will be deployed on Amazon EC2 instance. I would like to serve these files back out to the webapp consumers via an s3 bucket based domain (i.e. uploads.myapp.com). </p> <p>When the user uploads the files, I can easily drop them in into a folder called "site_uploads" on the local ec2 instance. However, since my ec2 instance has finite storage, with a lot of uploads, the ec2 file system will fill up quickly. </p> <p>It would be great if the ec2 instance could mount and s3 bucket as the "site_upload" directory. So that uploads to the EC2 "site_upload" directory <em>automatically</em> end up on uploads.myapp.com (and my webapp can use template tags to make sure the links for this uploaded content is based on that s3 backed domain). This also gives me scalable file serving, as request for files hits s3 and not my ec2 instance. Also, it makes it easy for my webapp to perform scaling/resizing of the images that appear locally in "site_upload" but are actually on s3.</p> <p>I'm looking at s3fs, but judging from the comments, it doesn't look like a fully baked solution. I'm looking for a non-commercial solution.</p> <p>FYI, The webapp is written in django, not that that changes the particulars too much. </p>
4
2009-06-05T16:39:25Z
6,308,720
<p>I'd suggest using a separately-mounted EBS volume. I tried doing the same thing for some movie files. Access to S3 was slow, and S3 has some limitations like not being able to rename files, no real directory structure, etc.</p> <p>You can set up EBS volumes in a RAID5 configuration and add space as you need it.</p>
0
2011-06-10T15:39:22Z
[ "python", "django", "amazon-s3", "amazon-ec2" ]
How to access the parent class during initialisation in python?
956,994
<p>How do I find out which class I am initialising a decorator in? It makes sense that I wouldn't be able to find this out as the decorator is not yet bound to the class, but is there a way of getting round this?</p> <pre><code>class A(object): def dec(f): # I am in class 'A' def func(cls): f(cls) return func @dec def test(self): pass </code></pre> <p>I need to know which class I am (indicated by the commented line).</p>
2
2009-06-05T17:03:40Z
957,245
<p>I don't think this is possible. At the very moment when you define test, the class doesn't exist yet.</p> <p>When Python encounters</p> <pre><code>class A(object): </code></pre> <p>it creates a new namespace in which it runs all code that it finds in the class definition (including the definition of test() and the call to the decorator), and when it's done, it creates a new class object and puts everything into this class that was left in the namespace after the code was executed.</p> <p>So when the decorator is called, it doesn't know anything yet. At this moment, test is just a function.</p>
3
2009-06-05T18:01:20Z
[ "python", "decorator", "introspection" ]
How to access the parent class during initialisation in python?
956,994
<p>How do I find out which class I am initialising a decorator in? It makes sense that I wouldn't be able to find this out as the decorator is not yet bound to the class, but is there a way of getting round this?</p> <pre><code>class A(object): def dec(f): # I am in class 'A' def func(cls): f(cls) return func @dec def test(self): pass </code></pre> <p>I need to know which class I am (indicated by the commented line).</p>
2
2009-06-05T17:03:40Z
957,312
<p>I don't get the question.</p> <pre><code>&gt;&gt;&gt; class A(object): def dec(f): def func(cls): print cls return func @dec def test(self): pass &gt;&gt;&gt; a=A() &gt;&gt;&gt; a.test() &lt;__main__.A object at 0x00C56330&gt; &gt;&gt;&gt; </code></pre> <p>The argument (<code>cls</code>) is the class, <code>A</code>.</p>
0
2009-06-05T18:17:42Z
[ "python", "decorator", "introspection" ]
How to access the parent class during initialisation in python?
956,994
<p>How do I find out which class I am initialising a decorator in? It makes sense that I wouldn't be able to find this out as the decorator is not yet bound to the class, but is there a way of getting round this?</p> <pre><code>class A(object): def dec(f): # I am in class 'A' def func(cls): f(cls) return func @dec def test(self): pass </code></pre> <p>I need to know which class I am (indicated by the commented line).</p>
2
2009-06-05T17:03:40Z
959,504
<p>As Nadia pointed out you will need to be more specific. Python does not allow this kind of things, which means that what you are trying to do is probably something wrong.</p> <p>In the meantime, here is my contribution: a little story about a sailor and a frog. (use a constructor <em>after</em> the class initialization)</p> <pre><code>class Cruise(object): def arewelostyet(self): print 'Young sailor: I think I am lost, help me :s' instance = Cruise() instance.arewelostyet() def whereami(lostfunc): """ decorator """ def decorated(*args, **kwargs): lostfunc(*args, **kwargs) print 'Frog: Crôak! thou art sailing in class', lostfunc.im_class.__name__ # don't forget to write name and doc decorated.func_name = lostfunc.func_name decorated.func_doc = lostfunc.func_name return decorated print '[i]A frog pops out of nowhere[/i]' # decorate the method: Cruise.arewelostyet = whereami(Cruise.arewelostyet) instance.arewelostyet() </code></pre>
0
2009-06-06T11:30:38Z
[ "python", "decorator", "introspection" ]
What robot (web) libraries are available for python?
957,661
<p>Specifically, are there any libraries that do not use sockets? I will be running this code in Google App Engine, which does not allow the use of sockets.</p> <p>Google app engine does allow the use of urllib2 to make web requests.</p> <p>I've been trying to get mechanize to work, since that what I've used before, but if there's something easier, I'd rather do that.</p> <p>thanks, Mark</p>
1
2009-06-05T19:20:23Z
967,176
<p>To answer your question, <a href="http://twill.idyll.org/" rel="nofollow">twill</a> and <a href="http://webunit.sourceforge.net/" rel="nofollow">webunit</a> are some other Python programmatic web browsing libraries. However, I'd be surprised if any of them worked off the bat with Google App Engine given the restricted stdlib.</p>
0
2009-06-08T21:42:47Z
[ "python", "google-app-engine", "robot" ]
What robot (web) libraries are available for python?
957,661
<p>Specifically, are there any libraries that do not use sockets? I will be running this code in Google App Engine, which does not allow the use of sockets.</p> <p>Google app engine does allow the use of urllib2 to make web requests.</p> <p>I've been trying to get mechanize to work, since that what I've used before, but if there's something easier, I'd rather do that.</p> <p>thanks, Mark</p>
1
2009-06-05T19:20:23Z
1,151,688
<p><a href="http://code.google.com/appengine/docs/python/urlfetch/" rel="nofollow">urlfetch</a> seems to do the same thing that you are looking for.</p>
1
2009-07-20T04:19:41Z
[ "python", "google-app-engine", "robot" ]
Is mod_wsgi/Python optimizing things out?
957,685
<p>I have been trying to track down weird problems with my mod_wsgi/Python web application. I have the application handler which creates an object and calls a method:</p> <pre><code>def my_method(self, file): self.sapi.write("In my method for %d time"%self.mmcount) self.mmcount += 1 # ... open file (absolute path to file), extract list of files inside # ... exit if file contains no path/file strings for f in extracted_files: self.num_files_found += 1 self.my_method(f) </code></pre> <p>At the start and end of this, I write</p> <pre><code>obj.num_files_found </code></pre> <p>To the browser.</p> <p>So this is a recursive function that goes down a tree of file-references inside files. Any references in a file are printed and then those references are opened and examined and so on until all files are leaf-nodes containing no files. Why I am doing this isn't really important ... it is more of a pedantic example.</p> <p><strong>You would expect the output to be deterministic</strong></p> <p>Such as</p> <pre><code>Files found: 0 In my method for the 0 time In my method for the 1 time In my method for the 2 time In my method for the 3 time ... In my method for the n time Files found: 128 </code></pre> <p>And <strong>for the first few requests it is as expected.</strong> Then I get the following for as long as I refresh</p> <pre><code>Files found: 0 In my method for the 0 time Files found: 128 </code></pre> <p>Even though I know, from previous refreshes and no code/file alterations that it takes <em>n</em> times to enumerate 128 files.</p> <p>So the question then: <strong>Does mod_wsgi/Python include internal optimizations that would stop complete execution? Does it guess the output is deterministic and cache?</strong></p> <p>As a note, in the refreshes when it is as expected, REMOTE_PORT increments by one each time ... when it uses a short output, the increment of REMOTE_PORT jumps wildly. Might be unrelated however.</p> <p><strong>I am new to Python, be gentle</strong></p> <p><strong>Solved</strong></p> <p>Who knows what it was, but ripping out Apache, mod_python, mod_wsgi and nearly everything HTTP related and re-installing fixed the problem. Something was <strong>pretty broken</strong> but seems ok now :)</p>
2
2009-06-05T19:25:33Z
957,758
<p>"Does mod_wsgi/Python include internal optimizations that would stop complete execution? Does it guess the output is deterministic and cache?"</p> <p>No.</p> <p>The problem is (generally) that you have a global variable somewhere in your program that is not getting reset the way you hoped it would.</p> <p>Sometimes this can be unintentional, since Python checks local namespace and global namespace for variables.</p> <p>You can -- inadvertently -- have a function that depends on some global variable. I'd bet on this. </p> <p>What you're likely seeing is a number of mod_wsgi daemon processes, each with a global variable problem. The first request for each daemon works. Then your global variable is in a state that prevents work from happening. [File is left open, top-level directory variable got overwritten, who knows?]</p> <p>After the first few, all the daemons are stuck in the "other" mode where they report the answer without doing the real work.</p>
1
2009-06-05T19:39:29Z
[ "python", "debugging", "caching", "mod-wsgi" ]
Is mod_wsgi/Python optimizing things out?
957,685
<p>I have been trying to track down weird problems with my mod_wsgi/Python web application. I have the application handler which creates an object and calls a method:</p> <pre><code>def my_method(self, file): self.sapi.write("In my method for %d time"%self.mmcount) self.mmcount += 1 # ... open file (absolute path to file), extract list of files inside # ... exit if file contains no path/file strings for f in extracted_files: self.num_files_found += 1 self.my_method(f) </code></pre> <p>At the start and end of this, I write</p> <pre><code>obj.num_files_found </code></pre> <p>To the browser.</p> <p>So this is a recursive function that goes down a tree of file-references inside files. Any references in a file are printed and then those references are opened and examined and so on until all files are leaf-nodes containing no files. Why I am doing this isn't really important ... it is more of a pedantic example.</p> <p><strong>You would expect the output to be deterministic</strong></p> <p>Such as</p> <pre><code>Files found: 0 In my method for the 0 time In my method for the 1 time In my method for the 2 time In my method for the 3 time ... In my method for the n time Files found: 128 </code></pre> <p>And <strong>for the first few requests it is as expected.</strong> Then I get the following for as long as I refresh</p> <pre><code>Files found: 0 In my method for the 0 time Files found: 128 </code></pre> <p>Even though I know, from previous refreshes and no code/file alterations that it takes <em>n</em> times to enumerate 128 files.</p> <p>So the question then: <strong>Does mod_wsgi/Python include internal optimizations that would stop complete execution? Does it guess the output is deterministic and cache?</strong></p> <p>As a note, in the refreshes when it is as expected, REMOTE_PORT increments by one each time ... when it uses a short output, the increment of REMOTE_PORT jumps wildly. Might be unrelated however.</p> <p><strong>I am new to Python, be gentle</strong></p> <p><strong>Solved</strong></p> <p>Who knows what it was, but ripping out Apache, mod_python, mod_wsgi and nearly everything HTTP related and re-installing fixed the problem. Something was <strong>pretty broken</strong> but seems ok now :)</p>
2
2009-06-05T19:25:33Z
957,932
<p>It seems the Python/mod_wsgi installation must be broken. I have never seen such weird bugs. Traces next to returns:</p> <pre><code>self.sapi.write("Returning at line 22 for call %d"%self.times_called) return someval </code></pre> <p>Appear to happen numerous time:</p> <blockquote> <p>Returning at line 22 for call 3</p> <p>Returning at line 22 for call 3</p> <p>Returning at line 22 for call 3</p> </blockquote> <p>There is just no consistent logic in the control-flow of anything :( I am also pretty sure that I can write simple incrementing code to count the number of times a method is called. Absolute, frustrating, nonsense. I even put epoch time next to every call to sapi.write() to make sure that wasn't mindlessly repeating code. They are unique :S</p> <p>Time to rip-out Apache, Python, mod_wsgi and the rest and start again.</p> <p><strong>Solved</strong></p> <p>Who knows what it was, but ripping out Apache, mod_python, mod_wsgi and nearly everything HTTP related and re-installing fixed the problem. Something was <strong>pretty broken</strong> but seems ok now :)</p>
1
2009-06-05T20:18:33Z
[ "python", "debugging", "caching", "mod-wsgi" ]
Is mod_wsgi/Python optimizing things out?
957,685
<p>I have been trying to track down weird problems with my mod_wsgi/Python web application. I have the application handler which creates an object and calls a method:</p> <pre><code>def my_method(self, file): self.sapi.write("In my method for %d time"%self.mmcount) self.mmcount += 1 # ... open file (absolute path to file), extract list of files inside # ... exit if file contains no path/file strings for f in extracted_files: self.num_files_found += 1 self.my_method(f) </code></pre> <p>At the start and end of this, I write</p> <pre><code>obj.num_files_found </code></pre> <p>To the browser.</p> <p>So this is a recursive function that goes down a tree of file-references inside files. Any references in a file are printed and then those references are opened and examined and so on until all files are leaf-nodes containing no files. Why I am doing this isn't really important ... it is more of a pedantic example.</p> <p><strong>You would expect the output to be deterministic</strong></p> <p>Such as</p> <pre><code>Files found: 0 In my method for the 0 time In my method for the 1 time In my method for the 2 time In my method for the 3 time ... In my method for the n time Files found: 128 </code></pre> <p>And <strong>for the first few requests it is as expected.</strong> Then I get the following for as long as I refresh</p> <pre><code>Files found: 0 In my method for the 0 time Files found: 128 </code></pre> <p>Even though I know, from previous refreshes and no code/file alterations that it takes <em>n</em> times to enumerate 128 files.</p> <p>So the question then: <strong>Does mod_wsgi/Python include internal optimizations that would stop complete execution? Does it guess the output is deterministic and cache?</strong></p> <p>As a note, in the refreshes when it is as expected, REMOTE_PORT increments by one each time ... when it uses a short output, the increment of REMOTE_PORT jumps wildly. Might be unrelated however.</p> <p><strong>I am new to Python, be gentle</strong></p> <p><strong>Solved</strong></p> <p>Who knows what it was, but ripping out Apache, mod_python, mod_wsgi and nearly everything HTTP related and re-installing fixed the problem. Something was <strong>pretty broken</strong> but seems ok now :)</p>
2
2009-06-05T19:25:33Z
1,038,152
<p>That Apache/mod_wsgi may run in both multi process/multi threaded configurations can trip up code which is written with the assumption that it is run in a single process, with that process possibly being single threaded. For a discussion of different configuration possibilities and what that all means for shared data, see:</p> <p><a href="http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading" rel="nofollow">http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading</a></p>
3
2009-06-24T12:47:20Z
[ "python", "debugging", "caching", "mod-wsgi" ]
How can I determine if one PGArray is included in another using SQLAlchemy sessions?
957,762
<p>I have an SqlAlchemy table like so:</p> <pre><code>table = sql.Table('treeItems', META, sql.Column('id', sql.Integer(), primary_key=True), sql.Column('type', sql.String, nullable=False), sql.Column('parentId', sql.Integer, sql.ForeignKey('treeItems.id')), sql.Column('lineage', PGArray(sql.Integer)), sql.Column('depth', sql.Integer), )</code></pre> <p>Which is mapped to an object like so:</p> <pre><code>orm.mapper(TreeItem, TreeItem.table, polymorphic_on=TreeItem.table.c.type, polymorphic_identity='TreeItem')</code></pre> <p>I'd like to select any child node of a given node so what I'm looking for is SQL that looks like this (for a parent with pk=2):</p> <pre><code>SELECT * FROM "treeItems" WHERE ARRAY[2] &lt;@ "treeItems".lineage AND "treeItems".id != 2 ORDER BY "treeItems".lineage</code></pre> <p>Here is the SqlAlchemy/Python code I use to try to get to the above SQL with little luck:</p> <pre><code>arrayStr = 'ARRAY[%s]' % ','.join([str(i) for i in self.lineage]) lineageFilter = expr.text('%s &lt;@ %s' % (arrayStr, TreeItem.table.c.lineage)) query = SESSION.query(TreeItem).filter(expr.and_(lineageFilter, TreeItem.table.c.id!=self.id))</code></pre> <p>But here is the SQL I wind up with (notice the lack of quotes around the treeItems table name in the where clause):</p> <pre><code>SELECT "treeItems".id AS "treeItems_id", "treeItems".type AS "treeItems_type", "treeItems"."parentId" AS "treeItems_parentId", "treeItems".lineage AS "treeItems_lineage", "treeItems".depth AS "treeItems_depth" FROM "treeItems" WHERE ARRAY[2] &lt;@ treeItems.lineage AND "treeItems".id != %(id_1)s</code></pre> <p>So, now for the questions:</p> <p><strong>Is there a better way to do this than to use the text() expression / Is there an operator or expression in SqlAlchemy that can do &lt;@ with PGArray?</strong></p> <p><strong>How can I get the quotes to show up around my table name if I must use the text() expression?</strong></p> <p>Thanks everyone!</p>
1
2009-06-05T19:40:14Z
958,314
<p>SQLAlchemy's clause elements have an .op() method for custom operators. What isn't available is a special clause for array literals. You can specify the array literal with literal_column:</p> <pre><code>print sql.literal_column('ARRAY[2]').op('&lt;@')(table.c.lineage) # ARRAY[2] &lt;@ "treeItems".lineage </code></pre> <p>If you want a better API for array literals, then you can create it with the <a href="http://www.sqlalchemy.org/docs/05/reference/ext/compiler.html" rel="nofollow">sqlalchemy.ext.compiler</a> module added in SQLAlchemy 0.5.4.</p>
4
2009-06-05T21:53:39Z
[ "python", "arrays", "postgresql", "sqlalchemy" ]
How can I determine if one PGArray is included in another using SQLAlchemy sessions?
957,762
<p>I have an SqlAlchemy table like so:</p> <pre><code>table = sql.Table('treeItems', META, sql.Column('id', sql.Integer(), primary_key=True), sql.Column('type', sql.String, nullable=False), sql.Column('parentId', sql.Integer, sql.ForeignKey('treeItems.id')), sql.Column('lineage', PGArray(sql.Integer)), sql.Column('depth', sql.Integer), )</code></pre> <p>Which is mapped to an object like so:</p> <pre><code>orm.mapper(TreeItem, TreeItem.table, polymorphic_on=TreeItem.table.c.type, polymorphic_identity='TreeItem')</code></pre> <p>I'd like to select any child node of a given node so what I'm looking for is SQL that looks like this (for a parent with pk=2):</p> <pre><code>SELECT * FROM "treeItems" WHERE ARRAY[2] &lt;@ "treeItems".lineage AND "treeItems".id != 2 ORDER BY "treeItems".lineage</code></pre> <p>Here is the SqlAlchemy/Python code I use to try to get to the above SQL with little luck:</p> <pre><code>arrayStr = 'ARRAY[%s]' % ','.join([str(i) for i in self.lineage]) lineageFilter = expr.text('%s &lt;@ %s' % (arrayStr, TreeItem.table.c.lineage)) query = SESSION.query(TreeItem).filter(expr.and_(lineageFilter, TreeItem.table.c.id!=self.id))</code></pre> <p>But here is the SQL I wind up with (notice the lack of quotes around the treeItems table name in the where clause):</p> <pre><code>SELECT "treeItems".id AS "treeItems_id", "treeItems".type AS "treeItems_type", "treeItems"."parentId" AS "treeItems_parentId", "treeItems".lineage AS "treeItems_lineage", "treeItems".depth AS "treeItems_depth" FROM "treeItems" WHERE ARRAY[2] &lt;@ treeItems.lineage AND "treeItems".id != %(id_1)s</code></pre> <p>So, now for the questions:</p> <p><strong>Is there a better way to do this than to use the text() expression / Is there an operator or expression in SqlAlchemy that can do &lt;@ with PGArray?</strong></p> <p><strong>How can I get the quotes to show up around my table name if I must use the text() expression?</strong></p> <p>Thanks everyone!</p>
1
2009-06-05T19:40:14Z
959,094
<p>In this particular case I noticed that the quoting in the SQL was due to the fact I was using a table name that was mixed case. Converting the table name from 'treeItems' to 'tree_items' resolved the quoting issue and I was able to get my text expression to work:</p> <pre><code>expr.text('%s &lt;@ %s' % (arrayStr, TreeItem.table.c.lineage))</code></pre> <p>It is a fix and it is nice to know that mixed case table names need to be quoted but Ants' answer remains the proper way to address the issue.</p>
0
2009-06-06T05:52:33Z
[ "python", "arrays", "postgresql", "sqlalchemy" ]
Is storm Python 3 compatible?
957,773
<p>I haven't found any information on that topic and its <a href="http://storm.canonical.com" rel="nofollow">homepage</a> doesn't mention it.</p>
3
2009-06-05T19:42:33Z
957,843
<p>Even though planned, at the moment there is no support for Python 3, you can check it out more details about that reading this thread from the storm ml:</p> <p><a href="https://lists.ubuntu.com/archives/storm/2009-January/000839.html" rel="nofollow">https://lists.ubuntu.com/archives/storm/2009-January/000839.html</a></p>
3
2009-06-05T19:57:03Z
[ "python", "python-3.x", "storm-orm" ]
Python disable/redirect keyboard input
958,491
<p>I'm writing a macro generator/ keyboard remapper in python, for xubuntu.</p> <p>I've figured out how to intercept and record keystrokes, and send keystrokes I want to record, but I haven't figured out how to block keystrokes. I need to disable keyboard input to remap a key. For example, if I wanted to send 'a' when I press the 's' key, I can currently record the 'a' keystroke, and set it to playback when I press the 's' key. I cannot, however keep the 's' keystroke from being sent alongside it.</p> <p>I used the pyxhook module from an open source keyboard-logger for the hooks, and a again, the xtest fake input method from the python x library.</p> <p>I remember reading somewhere about somebody blocking all keyboard input by redirecting all keystrokes to an invisible window by using tkinter. If somebody could post that method that'd be great. </p> <p>I need something that will block all keystrokes, but not turn off my keyboard hooks. </p>
3
2009-06-05T22:51:06Z
981,709
<p>I think it's going to depend heavily on the environment: curses &amp; the activestate recipe are good for command line, but if you want it to run in a DE, you'll need some hooks to that DE. You might look at Qt or GTK bindings for python, or there's a python-xlib library that might let you tie right into the X system.</p> <p>So I guess the answer is "it depends." Are you looking for console noecho functionality, or a text replacement program for a DE, or an xmodmap-style layout changer?</p>
1
2009-06-11T15:09:49Z
[ "python", "keyboard" ]
Python disable/redirect keyboard input
958,491
<p>I'm writing a macro generator/ keyboard remapper in python, for xubuntu.</p> <p>I've figured out how to intercept and record keystrokes, and send keystrokes I want to record, but I haven't figured out how to block keystrokes. I need to disable keyboard input to remap a key. For example, if I wanted to send 'a' when I press the 's' key, I can currently record the 'a' keystroke, and set it to playback when I press the 's' key. I cannot, however keep the 's' keystroke from being sent alongside it.</p> <p>I used the pyxhook module from an open source keyboard-logger for the hooks, and a again, the xtest fake input method from the python x library.</p> <p>I remember reading somewhere about somebody blocking all keyboard input by redirecting all keystrokes to an invisible window by using tkinter. If somebody could post that method that'd be great. </p> <p>I need something that will block all keystrokes, but not turn off my keyboard hooks. </p>
3
2009-06-05T22:51:06Z
993,251
<p>I've got a keyboard hook that detects X events. I'm looking for a way to globally prevent a single keyboard event from being sent to a window. Something that works by accessing the event queue and removing the keyboard event from it would be ideal. It looks like it should be possible using Python Xlib, but I can't figure it out. </p>
0
2009-06-14T17:22:46Z
[ "python", "keyboard" ]
Find all possible factors in KenKen puzzle 'multiply' domain
958,678
<p>A KenKen puzzle is a Latin square divided into edge-connected domains: a single cell, two adjacent cells within the same row or column, three cells arranged in a row or in an ell, etc. Each domain has a label which gives a target number and a single arithmetic operation (+-*/) which is to be applied to the numbers in the cells of the domain to yield the target number. (If the domain has just one cell, there is no operator given, just a target --- the square is solved for you. If the operator is - or /, then there are just two cells in the domain.) The aim of the puzzle is to (re)construct the Latin square consistent with the domains' boundaries and labels. (I think that I have seen a puzzle with a non-unique solution just once.)</p> <p>The number in a cell can range from 1 to the width (height) of the puzzle; commonly, puzzles are 4 or 6 cells on a side, but consider puzzles of any size. Domains in published puzzles (4x4 or 6x6) typically have no more than 5 cells, but, again, this does not seem to be a hard limit. (However, if the puzzle had just one domain, there would be as many solutions as there are Latin squares of that dimension...)</p> <p>A first step to writing a KenKen solver would be to have routines that can produce the possible combinations of numbers in any domain, at first neglecting the domain's geometry. (A linear domain, like a line of three cells, cannot have duplicate numbers in the solved puzzle, but we ignore this for the moment.) I've been able to write a Python function which handles addition labels case by case: give it the width of the puzzle, the number of cells in the domain, and the target sum, and it returns a list of tuples of valid numbers adding up to the target.</p> <p>The multiplication case eludes me. I can get a dictionary with keys equal to the products attainable in a domain of a given size in a puzzle of a given size, with the values being lists of tuples containing the factors giving the product, but I can't work out a case-by-case routine, not even a bad one.</p> <p>Factoring a given product into primes seems easy, but then partitioning the list of primes into the desired number of factors stumps me. (I have meditated on Fascicle 3 of Volume 4 of Knuth's TAOCP, but I have not learned how to 'grok' his algorithm descriptions, so I do not know whether his algorithms for set partitioning would be a starting point. Understanding Knuth's descriptions could be another question!)</p> <p>I'm quite happy to precompute the 'multiply' dictionaries for common domain and puzzle sizes and just chalk the loading time up to overhead, but that approach would not seem an efficient way to deal with, say, puzzles 100 cells on a side and domains from 2 to 50 cells in size. </p>
3
2009-06-06T00:42:39Z
959,135
<p>Simplified goal: you need to enumerate all integer combinations that multiply together to form a certain product, where the number of integers is fixed.</p> <p>To solve this, all you need is a prime factorization of your target number, and then use a combinatorial approach to form all possible sub-products from these factors. (There are also a few other constraints of the puzzle that are easy to include once you have all possible sub-products, like no entry can be great than <code>max_entry</code>, and you have a fixed number of integers to use, <code>n_boxes_in_domain</code>.)</p> <p>For example, if <code>max_entry=6</code>, <code>n_boxes_in_domain=3</code>, and the <code>target_number=20</code>: 20 yields (2, 2, 5); which goes to (2, 2, 5) and (1, 4, 5).</p> <p>The trick to this is to form all possible sub-products, and the code below does this. It works by looping through the factors forming all possible single pairs, and then doing this recursively, to give all possible sets of all single or multiple pairings. (It's inefficiently, but even large numbers have a small prime factorization):</p> <pre><code>def xgroup(items): L = len(items) for i in range(L-1): for j in range(1, L): temp = list(items) a = temp.pop(j) b = temp.pop(i) temp.insert(0, a*b) yield temp for x in xgroup(temp): yield x def product_combos(max_entry, n_boxes, items): r = set() if len(items)&lt;=n_boxes: r.add(tuple(items)) for i in xgroup(items): x = i[:] x.sort() if x[-1]&lt;=max_entry and len(x)&lt;=n_boxes: r.add(tuple(x)) r = [list(i) for i in r] r.sort() for i in r: while len(i)&lt;n_boxes: i.insert(0, 1) return r </code></pre> <p>I'll leave it to you to generate the prime factors, but this seems to work for</p> <pre><code>max_entry=6, n_boxes=3, items=(2,2,5) [2, 2, 5] [1, 4, 5] </code></pre> <p>and for a harder case where, say <code>target_number=2106</code> </p> <pre><code>max_entry=50, n_boxes=6, items=(2,3,3,3,3,13) [2, 3, 3, 3, 3, 13] [1, 2, 3, 3, 3, 39] [1, 2, 3, 3, 9, 13] [1, 1, 2, 3, 9, 39] [1, 1, 2, 3, 13, 27] [1, 1, 2, 9, 9, 13] [1, 1, 1, 2, 27, 39] [1, 3, 3, 3, 3, 26] [1, 3, 3, 3, 6, 13] [1, 1, 3, 3, 6, 39] [1, 1, 3, 3, 9, 26] [1, 1, 3, 3, 13, 18] [1, 1, 3, 6, 9, 13] [1, 1, 1, 3, 18, 39] [1, 1, 1, 3, 26, 27] [1, 1, 1, 6, 9, 39] [1, 1, 1, 6, 13, 27] [1, 1, 1, 9, 9, 26] [1, 1, 1, 9, 13, 18] </code></pre>
4
2009-06-06T06:35:33Z
[ "python", "algorithm", "partitioning", "prime-factoring" ]
Clean Python Regular Expressions
958,853
<p>Is there a cleaner way to write long regex patterns in python? I saw this approach somewhere but regex in python doesn't allow lists.</p> <pre><code>patterns = [ re.compile(r'&lt;!--([^-&gt;]|(-+[^-&gt;])|(-?&gt;))*-{2,}&gt;'), re.compile(r'\n+|\s{2}') ] </code></pre>
12
2009-06-06T02:21:57Z
958,860
<p>You can use verbose mode to write more readable regular expressions. In this mode:</p> <ul> <li>Whitespace within the pattern is ignored, except when in a character class or preceded by an unescaped backslash.</li> <li>When a line contains a '#' neither in a character class or preceded by an unescaped backslash, all characters from the leftmost such '#' through the end of the line are ignored.</li> </ul> <p>The following two statements are equivalent:</p> <pre><code>a = re.compile(r"""\d + # the integral part \. # the decimal point \d * # some fractional digits""", re.X) b = re.compile(r"\d+\.\d*") </code></pre> <p>(Taken from the documentation of <a href="http://docs.python.org/library/re.html#re.VERBOSE">verbose mode</a>)</p>
22
2009-06-06T02:25:01Z
[ "python", "regex", "list" ]
Clean Python Regular Expressions
958,853
<p>Is there a cleaner way to write long regex patterns in python? I saw this approach somewhere but regex in python doesn't allow lists.</p> <pre><code>patterns = [ re.compile(r'&lt;!--([^-&gt;]|(-+[^-&gt;])|(-?&gt;))*-{2,}&gt;'), re.compile(r'\n+|\s{2}') ] </code></pre>
12
2009-06-06T02:21:57Z
958,861
<p>You can use comments in regex's, which make them much more readable. Taking an example from <a href="http://gnosis.cx/publish/programming/regular_expressions.html" rel="nofollow">http://gnosis.cx/publish/programming/regular_expressions.html</a> :</p> <pre><code>/ # identify URLs within a text file [^="] # do not match URLs in IMG tags like: # &lt;img src="http://mysite.com/mypic.png"&gt; http|ftp|gopher # make sure we find a resource type :\/\/ # ...needs to be followed by colon-slash-slash [^ \n\r]+ # stuff other than space, newline, tab is in URL (?=[\s\.,]) # assert: followed by whitespace/period/comma / </code></pre>
2
2009-06-06T02:25:18Z
[ "python", "regex", "list" ]
Clean Python Regular Expressions
958,853
<p>Is there a cleaner way to write long regex patterns in python? I saw this approach somewhere but regex in python doesn't allow lists.</p> <pre><code>patterns = [ re.compile(r'&lt;!--([^-&gt;]|(-+[^-&gt;])|(-?&gt;))*-{2,}&gt;'), re.compile(r'\n+|\s{2}') ] </code></pre>
12
2009-06-06T02:21:57Z
958,890
<p>Though @Ayman's suggestion about <code>re.VERBOSE</code> is a better idea, if all you want is what you're showing, just do:</p> <pre><code>patterns = re.compile( r'&lt;!--([^-&gt;]|(-+[^-&gt;])|(-?&gt;))*-{2,}&gt;' r'\n+|\s{2}' ) </code></pre> <p>and Python's automatic concatenation of adjacent string literals (much like C's, btw) will do the rest;-).</p>
12
2009-06-06T02:58:07Z
[ "python", "regex", "list" ]
Python function calls are bleeding scope, stateful, failing to initialize parameters?
959,113
<p>Before I have the audacity to file a bug report, I thought I'd check my assumptions among wiser Pythonistas here. I encountered a baffling case today, so I whittled it down to a toy example, shown below:</p> <pre><code>#!/usr/bin/env python # -*- coding: UTF-8 -*- """ A little script to demonstrate that a function won't re-initialize its list parameters between calls, but instead allows them to retain state. """ def bleedscope(a=[], b=[]): """ On each call, unless explicitly passed, both `a` and `b` should be initialized as empty lists. """ c = a if b: c.extend(b) return len(c) x = bleedscope(b=[1]) print x # Should be 1, as expected. x = bleedscope(b=[2]) print x # Expect also to be 1, but it's 2. `a` is retained. x = bleedscope(a=[1]) print x # Now 1 as expected. x = bleedscope(b=[3]) print x # 1 as expected? No, it's 3! Insanity! </code></pre> <p>I thought function arguments were local in scope to the function, and were garbage-collected at the end of a function call, never to retain state between them. I have tested the above script on Python 2.5.2 and Python 2.6.1, though, and my understanding does not the results. Argument <code>a</code> certainly retains state between most of these calls; the most perplexing one being the final call to <code>bleedscope</code>, where it skips the state of the previous call and goes back to the state at the end of the second (i.e., <code>[1, 2]</code>). [I suggest running this in your favorite debugger to see for yourself. If you don't have one, I suggest <a href="http://winpdb.org/" rel="nofollow">Winpdb</a> as a solid FOSS standalone Python debugger.]</p> <p>What's going on here?</p>
4
2009-06-06T06:15:00Z
959,118
<p>In Python default parameter values only get initialized when the def call is parsed. In the case of an object (such as your lists), it gets reused between calls. Take a look at this article about it, which also provides the necessary workaround:</p> <p><a href="http://effbot.org/zone/default-values.htm">http://effbot.org/zone/default-values.htm</a></p>
15
2009-06-06T06:20:01Z
[ "python", "scope" ]
Python function calls are bleeding scope, stateful, failing to initialize parameters?
959,113
<p>Before I have the audacity to file a bug report, I thought I'd check my assumptions among wiser Pythonistas here. I encountered a baffling case today, so I whittled it down to a toy example, shown below:</p> <pre><code>#!/usr/bin/env python # -*- coding: UTF-8 -*- """ A little script to demonstrate that a function won't re-initialize its list parameters between calls, but instead allows them to retain state. """ def bleedscope(a=[], b=[]): """ On each call, unless explicitly passed, both `a` and `b` should be initialized as empty lists. """ c = a if b: c.extend(b) return len(c) x = bleedscope(b=[1]) print x # Should be 1, as expected. x = bleedscope(b=[2]) print x # Expect also to be 1, but it's 2. `a` is retained. x = bleedscope(a=[1]) print x # Now 1 as expected. x = bleedscope(b=[3]) print x # 1 as expected? No, it's 3! Insanity! </code></pre> <p>I thought function arguments were local in scope to the function, and were garbage-collected at the end of a function call, never to retain state between them. I have tested the above script on Python 2.5.2 and Python 2.6.1, though, and my understanding does not the results. Argument <code>a</code> certainly retains state between most of these calls; the most perplexing one being the final call to <code>bleedscope</code>, where it skips the state of the previous call and goes back to the state at the end of the second (i.e., <code>[1, 2]</code>). [I suggest running this in your favorite debugger to see for yourself. If you don't have one, I suggest <a href="http://winpdb.org/" rel="nofollow">Winpdb</a> as a solid FOSS standalone Python debugger.]</p> <p>What's going on here?</p>
4
2009-06-06T06:15:00Z
959,121
<p>This is your problem:</p> <pre><code>def bleedscope(a=[], b=[]): </code></pre> <p>it should be</p> <pre><code>def bleedscope(a=None, b=None): if a is None: a = [] if b is None: b = [] </code></pre> <p>The default parameters are only executed once when the function is parsed, thus using the same 2 lists every time.</p>
8
2009-06-06T06:21:31Z
[ "python", "scope" ]
Python function calls are bleeding scope, stateful, failing to initialize parameters?
959,113
<p>Before I have the audacity to file a bug report, I thought I'd check my assumptions among wiser Pythonistas here. I encountered a baffling case today, so I whittled it down to a toy example, shown below:</p> <pre><code>#!/usr/bin/env python # -*- coding: UTF-8 -*- """ A little script to demonstrate that a function won't re-initialize its list parameters between calls, but instead allows them to retain state. """ def bleedscope(a=[], b=[]): """ On each call, unless explicitly passed, both `a` and `b` should be initialized as empty lists. """ c = a if b: c.extend(b) return len(c) x = bleedscope(b=[1]) print x # Should be 1, as expected. x = bleedscope(b=[2]) print x # Expect also to be 1, but it's 2. `a` is retained. x = bleedscope(a=[1]) print x # Now 1 as expected. x = bleedscope(b=[3]) print x # 1 as expected? No, it's 3! Insanity! </code></pre> <p>I thought function arguments were local in scope to the function, and were garbage-collected at the end of a function call, never to retain state between them. I have tested the above script on Python 2.5.2 and Python 2.6.1, though, and my understanding does not the results. Argument <code>a</code> certainly retains state between most of these calls; the most perplexing one being the final call to <code>bleedscope</code>, where it skips the state of the previous call and goes back to the state at the end of the second (i.e., <code>[1, 2]</code>). [I suggest running this in your favorite debugger to see for yourself. If you don't have one, I suggest <a href="http://winpdb.org/" rel="nofollow">Winpdb</a> as a solid FOSS standalone Python debugger.]</p> <p>What's going on here?</p>
4
2009-06-06T06:15:00Z
959,131
<p>Funnily enough, your input and your output are quite similar, for totally accidental reasons.</p> <p>Actually what happens with Python is that the default values for a and b in your method declaration are "static" values. They are instanciated once at the method definition. So your default "a" is pushed each time you do not pass an "a" as argument.</p> <p>Put a "print a" at the beginning of your method to see that happen.</p>
1
2009-06-06T06:33:59Z
[ "python", "scope" ]
Python function calls are bleeding scope, stateful, failing to initialize parameters?
959,113
<p>Before I have the audacity to file a bug report, I thought I'd check my assumptions among wiser Pythonistas here. I encountered a baffling case today, so I whittled it down to a toy example, shown below:</p> <pre><code>#!/usr/bin/env python # -*- coding: UTF-8 -*- """ A little script to demonstrate that a function won't re-initialize its list parameters between calls, but instead allows them to retain state. """ def bleedscope(a=[], b=[]): """ On each call, unless explicitly passed, both `a` and `b` should be initialized as empty lists. """ c = a if b: c.extend(b) return len(c) x = bleedscope(b=[1]) print x # Should be 1, as expected. x = bleedscope(b=[2]) print x # Expect also to be 1, but it's 2. `a` is retained. x = bleedscope(a=[1]) print x # Now 1 as expected. x = bleedscope(b=[3]) print x # 1 as expected? No, it's 3! Insanity! </code></pre> <p>I thought function arguments were local in scope to the function, and were garbage-collected at the end of a function call, never to retain state between them. I have tested the above script on Python 2.5.2 and Python 2.6.1, though, and my understanding does not the results. Argument <code>a</code> certainly retains state between most of these calls; the most perplexing one being the final call to <code>bleedscope</code>, where it skips the state of the previous call and goes back to the state at the end of the second (i.e., <code>[1, 2]</code>). [I suggest running this in your favorite debugger to see for yourself. If you don't have one, I suggest <a href="http://winpdb.org/" rel="nofollow">Winpdb</a> as a solid FOSS standalone Python debugger.]</p> <p>What's going on here?</p>
4
2009-06-06T06:15:00Z
961,780
<p>It's a <a href="http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects" rel="nofollow">FAQ</a>.</p>
4
2009-06-07T12:06:47Z
[ "python", "scope" ]
not able to start coding in python
959,168
<p>i want to code in python and i know the syntax well.. but i have got no idea how to compile and run it ..!! i mean i am from ruby , java , c , c++ background and there after saving it in a file we go to command prompt and type the command and the file name to compile and run it . then what about python ? why does python filename.py doesnt work ?</p> <p>and how to make a file run then ? and which python books to follow for better understanding </p> <p>i am using windows os .! and i dont want to run it line by line on the idle .. i want to write the whole code and then run it from windows command prompt</p>
-1
2009-06-06T07:18:26Z
959,172
<p>what operating system are you using?... you dont need to compile python code its interprated. just invoke the command line interpreter followed by the name of your .py file </p>
1
2009-06-06T07:22:46Z
[ "python" ]
not able to start coding in python
959,168
<p>i want to code in python and i know the syntax well.. but i have got no idea how to compile and run it ..!! i mean i am from ruby , java , c , c++ background and there after saving it in a file we go to command prompt and type the command and the file name to compile and run it . then what about python ? why does python filename.py doesnt work ?</p> <p>and how to make a file run then ? and which python books to follow for better understanding </p> <p>i am using windows os .! and i dont want to run it line by line on the idle .. i want to write the whole code and then run it from windows command prompt</p>
-1
2009-06-06T07:18:26Z
959,176
<p>If you're using Windows, you'll need to add the path to your Python executable to the Path environment variable; on Linux, and I presume Mac, this should already be done.</p> <p>Oh, and you don't compile python programs, they are interpreted at run time.</p>
4
2009-06-06T07:24:08Z
[ "python" ]
not able to start coding in python
959,168
<p>i want to code in python and i know the syntax well.. but i have got no idea how to compile and run it ..!! i mean i am from ruby , java , c , c++ background and there after saving it in a file we go to command prompt and type the command and the file name to compile and run it . then what about python ? why does python filename.py doesnt work ?</p> <p>and how to make a file run then ? and which python books to follow for better understanding </p> <p>i am using windows os .! and i dont want to run it line by line on the idle .. i want to write the whole code and then run it from windows command prompt</p>
-1
2009-06-06T07:18:26Z
960,052
<p>If you are from Ruby background, you should be able to handle another interpreted language, which is what python is too. </p> <p>Good starter resource:</p> <p><a href="http://www.diveintopython.net/" rel="nofollow">Dive into Python</a></p>
3
2009-06-06T16:20:26Z
[ "python" ]
Removing starting spaces in Python?
959,215
<p>I have a text string that starts with a number of spaces, varying between 2 &amp; 4. What's the easiest &amp; simplest way to remove them ie. remove everything before a certain character?</p>
51
2009-06-06T07:55:12Z
959,216
<p>The <a href="http://docs.python.org/library/stdtypes.html#str.lstrip"><code>lstrip()</code></a> method will remove leading whitespaces, newline and tab characters on a string beginning:</p> <pre><code>&gt;&gt;&gt; ' hello world!'.lstrip() 'hello world!' </code></pre> <p><strong>Edit</strong></p> <p>As balpha pointed out in the comments, in order to remove <em>only</em> spaces from the beginning of the string, <code>lstrip(' ')</code> should be used:</p> <pre><code>&gt;&gt;&gt; ' hello world with 2 spaces and a tab!'.lstrip(' ') '\thello world with 2 spaces and a tab!' </code></pre> <p>Related question:</p> <ul> <li><a href="http://stackoverflow.com/questions/761804/trimming-a-string-in-python">Trimming a string in Python</a></li> </ul>
118
2009-06-06T07:57:22Z
[ "python", "string", "trim" ]
Removing starting spaces in Python?
959,215
<p>I have a text string that starts with a number of spaces, varying between 2 &amp; 4. What's the easiest &amp; simplest way to remove them ie. remove everything before a certain character?</p>
51
2009-06-06T07:55:12Z
959,218
<p>The function <code>strip</code> will remove whitespace from the beginning and end of a string.</p> <pre><code>my_str = " text " my_str = my_str.strip() </code></pre> <p>will set <code>my_str</code> to <code>"text"</code>.</p>
24
2009-06-06T07:58:37Z
[ "python", "string", "trim" ]
Removing starting spaces in Python?
959,215
<p>I have a text string that starts with a number of spaces, varying between 2 &amp; 4. What's the easiest &amp; simplest way to remove them ie. remove everything before a certain character?</p>
51
2009-06-06T07:55:12Z
959,225
<p>To remove everything before a certain character, use a regular expression:</p> <pre><code>re.sub(r'^[^a]*', '') </code></pre> <p>to remove everything up to the first 'a'. <code>[^a]</code> can be replaced with any character class you like, such as word characters.</p>
5
2009-06-06T08:04:13Z
[ "python", "string", "trim" ]
Removing starting spaces in Python?
959,215
<p>I have a text string that starts with a number of spaces, varying between 2 &amp; 4. What's the easiest &amp; simplest way to remove them ie. remove everything before a certain character?</p>
51
2009-06-06T07:55:12Z
30,802,316
<p>If you want to cut the whitespaces before and behind the word, but keep the middle ones. <br> You could use: </p> <pre><code>word = ' Hello World ' stripped = word.strip() print(stripped) </code></pre>
0
2015-06-12T11:47:39Z
[ "python", "string", "trim" ]
Parsing numbers in Python
959,412
<p>i want to take inputs like this 10 12 </p> <p>13 14</p> <p>15 16</p> <p>..</p> <p>how to take this input , as two diffrent integers so that i can multiply them in python after every 10 and 12 there is newline</p>
2
2009-06-06T10:15:20Z
959,424
<p>You could use regular expressions (<code>re</code>-module)</p> <pre><code>import re test = "10 11\n12 13" # Get this input from the files or the console matches = re.findall(r"(\d+)\s*(\d+)", test) products = [ int(a) * int(b) for a, b in matches ] # Process data print(products) </code></pre>
0
2009-06-06T10:25:13Z
[ "python", "parsing" ]
Parsing numbers in Python
959,412
<p>i want to take inputs like this 10 12 </p> <p>13 14</p> <p>15 16</p> <p>..</p> <p>how to take this input , as two diffrent integers so that i can multiply them in python after every 10 and 12 there is newline</p>
2
2009-06-06T10:15:20Z
959,425
<p>I'm not sure I understood your problem very well, it seems you want to parse two int separated from a space.</p> <p>In python you do:</p> <pre><code>s = raw_input('Insert 2 integers separated by a space: ') a,b = [int(i) for i in s.split(' ')] print a*b </code></pre> <p>Explanation:</p> <pre><code>s = raw_input('Insert 2 integers separated by a space: ') </code></pre> <p>raw_input takes everything you type (until you press enter) and returns it as a string, so:</p> <pre><code>&gt;&gt;&gt; raw_input('Insert 2 integers separated by a space: ') Insert 2 integers separated by a space: 10 12 '10 12' </code></pre> <p>In s you have now '10 12', the two int are separated by a space, we split the string at the space with</p> <pre><code>&gt;&gt;&gt; s.split(' ') ['10', '12'] </code></pre> <p>now you have a list of strings, you want to convert them in int, so:</p> <pre><code>&gt;&gt;&gt; [int(i) for i in s.split(' ')] [10, 12] </code></pre> <p>then you assign each member of the list to a variable (a and b) and then you do the product a*b</p>
7
2009-06-06T10:25:34Z
[ "python", "parsing" ]
Parsing numbers in Python
959,412
<p>i want to take inputs like this 10 12 </p> <p>13 14</p> <p>15 16</p> <p>..</p> <p>how to take this input , as two diffrent integers so that i can multiply them in python after every 10 and 12 there is newline</p>
2
2009-06-06T10:15:20Z
959,426
<pre><code>f = open('inputfile.txt') for line in f.readlines(): # the next line is equivalent to: # s1, s2 = line.split(' ') # a = int(s1) # b = int(s2) a, b = map(int, line.split(' ')) print a*b </code></pre>
2
2009-06-06T10:26:30Z
[ "python", "parsing" ]
I need a beginners guide to setting up windows for python development
959,479
<p>I currently work with .NET exclusively and would like to have a go at python. To this end I need to set up a python development environment. I guide to this would be handy. I guess I would be doing web development so will need a web server and probably a database. I also need pointers to popular ORM's, an MVC framework, and a testing library.</p> <p>One of my main criteria with all this is that I want to understand how it works, and I want it to be as isolated as possible. This is important as i am wary of polluting what is a working .NET environment with 3rd party web and database servers. I am perfectly happy using SQLite to start with if this is possible.</p> <p>If I get on well with this I am also likely to want to set up automated build and ci server (On a virtual machine, probably ubuntu). Any suggestions for these would be useful.</p> <p>My ultimate aim if i like python is to have similar sorts of tools that i have available with .NET and to really understand the build and deployment of it all. To start with I will settle for a simple development environment that is as isolated as possible and will be easy to remove if I don't like it. I don't want to use IronPython as I want the full experience of developing a python solution using the tools and frameworks that are generally used. </p>
9
2009-06-06T11:08:51Z
959,492
<ul> <li><a href="http://docs.python.org/using/windows.html" rel="nofollow">Using Python on Windows</a></li> <li><a href="http://stackoverflow.com/questions/207701/python-tutorial-for-total-beginners">SO: Python tutorial for total beginners?</a></li> </ul>
2
2009-06-06T11:18:48Z
[ "python", "windows", "development-environment" ]
I need a beginners guide to setting up windows for python development
959,479
<p>I currently work with .NET exclusively and would like to have a go at python. To this end I need to set up a python development environment. I guide to this would be handy. I guess I would be doing web development so will need a web server and probably a database. I also need pointers to popular ORM's, an MVC framework, and a testing library.</p> <p>One of my main criteria with all this is that I want to understand how it works, and I want it to be as isolated as possible. This is important as i am wary of polluting what is a working .NET environment with 3rd party web and database servers. I am perfectly happy using SQLite to start with if this is possible.</p> <p>If I get on well with this I am also likely to want to set up automated build and ci server (On a virtual machine, probably ubuntu). Any suggestions for these would be useful.</p> <p>My ultimate aim if i like python is to have similar sorts of tools that i have available with .NET and to really understand the build and deployment of it all. To start with I will settle for a simple development environment that is as isolated as possible and will be easy to remove if I don't like it. I don't want to use IronPython as I want the full experience of developing a python solution using the tools and frameworks that are generally used. </p>
9
2009-06-06T11:08:51Z
959,494
<p>Well, if you're thinking of setting up an Ubuntu VM anyway, you might as well make that your development environment. Then you can install Apache and MySQL or Postgres on that VM just via the standard packaging tools (apt-get install), and there's no danger of polluting your Windows environment.</p> <p>You can either do the actual development on your Windows machine via your favourite IDE, using the VM as a networked drive and saving the code there, or you can just use the VM as a full desktop environment and do everything there, which is what I would recommend.</p>
3
2009-06-06T11:20:26Z
[ "python", "windows", "development-environment" ]
I need a beginners guide to setting up windows for python development
959,479
<p>I currently work with .NET exclusively and would like to have a go at python. To this end I need to set up a python development environment. I guide to this would be handy. I guess I would be doing web development so will need a web server and probably a database. I also need pointers to popular ORM's, an MVC framework, and a testing library.</p> <p>One of my main criteria with all this is that I want to understand how it works, and I want it to be as isolated as possible. This is important as i am wary of polluting what is a working .NET environment with 3rd party web and database servers. I am perfectly happy using SQLite to start with if this is possible.</p> <p>If I get on well with this I am also likely to want to set up automated build and ci server (On a virtual machine, probably ubuntu). Any suggestions for these would be useful.</p> <p>My ultimate aim if i like python is to have similar sorts of tools that i have available with .NET and to really understand the build and deployment of it all. To start with I will settle for a simple development environment that is as isolated as possible and will be easy to remove if I don't like it. I don't want to use IronPython as I want the full experience of developing a python solution using the tools and frameworks that are generally used. </p>
9
2009-06-06T11:08:51Z
959,497
<p>Install the pre-configured <a href="http://www.activestate.com/activepython/" rel="nofollow">ActivePython</a> release from activestate. Among other features, it includes the PythonWin IDE (Windows only) which makes it easy to explore Python interactively.</p> <p>The recommended reference is <a href="http://www.diveintopython.net/" rel="nofollow"><em>Dive Into Python</em></a>, mentioned many times on similar SO discussions.</p>
3
2009-06-06T11:21:45Z
[ "python", "windows", "development-environment" ]
I need a beginners guide to setting up windows for python development
959,479
<p>I currently work with .NET exclusively and would like to have a go at python. To this end I need to set up a python development environment. I guide to this would be handy. I guess I would be doing web development so will need a web server and probably a database. I also need pointers to popular ORM's, an MVC framework, and a testing library.</p> <p>One of my main criteria with all this is that I want to understand how it works, and I want it to be as isolated as possible. This is important as i am wary of polluting what is a working .NET environment with 3rd party web and database servers. I am perfectly happy using SQLite to start with if this is possible.</p> <p>If I get on well with this I am also likely to want to set up automated build and ci server (On a virtual machine, probably ubuntu). Any suggestions for these would be useful.</p> <p>My ultimate aim if i like python is to have similar sorts of tools that i have available with .NET and to really understand the build and deployment of it all. To start with I will settle for a simple development environment that is as isolated as possible and will be easy to remove if I don't like it. I don't want to use IronPython as I want the full experience of developing a python solution using the tools and frameworks that are generally used. </p>
9
2009-06-06T11:08:51Z
959,512
<p>Take a look at <a href="http://pylonshq.com/" rel="nofollow">Pylons</a>, read about <a href="http://www.python.org/dev/peps/pep-0333/" rel="nofollow">WSGI</a> and <a href="http://pythonpaste.org/" rel="nofollow">Paste</a>. There's nice introductory Google tech talk about them: <a href="http://www.youtube.com/watch?v=Ui-mSFuUZmQ" rel="nofollow">ReUsable Web Components with Python and Future Python Web Development</a>.</p> <p>Here's my answer to similar question: <a href="http://stackoverflow.com/questions/702179/django-vs-other-python-web-frameworks/926169#926169">Django vs other Python web frameworks?</a></p>
2
2009-06-06T11:37:16Z
[ "python", "windows", "development-environment" ]
I need a beginners guide to setting up windows for python development
959,479
<p>I currently work with .NET exclusively and would like to have a go at python. To this end I need to set up a python development environment. I guide to this would be handy. I guess I would be doing web development so will need a web server and probably a database. I also need pointers to popular ORM's, an MVC framework, and a testing library.</p> <p>One of my main criteria with all this is that I want to understand how it works, and I want it to be as isolated as possible. This is important as i am wary of polluting what is a working .NET environment with 3rd party web and database servers. I am perfectly happy using SQLite to start with if this is possible.</p> <p>If I get on well with this I am also likely to want to set up automated build and ci server (On a virtual machine, probably ubuntu). Any suggestions for these would be useful.</p> <p>My ultimate aim if i like python is to have similar sorts of tools that i have available with .NET and to really understand the build and deployment of it all. To start with I will settle for a simple development environment that is as isolated as possible and will be easy to remove if I don't like it. I don't want to use IronPython as I want the full experience of developing a python solution using the tools and frameworks that are generally used. </p>
9
2009-06-06T11:08:51Z
959,738
<p>It's not that hard to set up a Python environment, and I've never had it muck up my .NET work. Basically, install Python --- I'd use 2.6 rather than 3.0, which is not yet broadly accepted --- and add it to your PATH, and you're ready to go with the language. I wouldn't recommend using a Ubuntu VM as your development environment; if you're working on Windows, you might as well develop on Windows, and I've had no significant problems doing so. I go back and forth from Windows to Linux with no trouble. </p> <p>If you have an editor that you're comfortable with that has basic support for Python, I'd stick with it. If not, I've found <a href="http://www.geany.org" rel="nofollow">Geany</a> to be a nice, light, easy-to-use editor with good Python support, though I use <a href="http://www.gnu.org/software/emacs/" rel="nofollow">Emacs</a> myself because I know it; other people like <a href="http://www.scintilla.org/SciTE.html" rel="nofollow">SCITE</a>, <a href="http://notepad-plus.sourceforge.net/" rel="nofollow">NotePad++</a>, or any of a slew of others. I'd avoid fancy IDEs for Python, because they don't match the character of the language, and I wouldn't bother with IDLE (included with Python), because it's a royal pain to use.</p> <p>Suggestions for libraries and frameworks:</p> <ul> <li><a href="http://www.djangoproject.org" rel="nofollow">Django</a> is the <em>standard</em> web framework, but it's big and you have to work django's way; I prefer <a href="http://www.cherrypy.org/" rel="nofollow">CherryPy</a>, which is also actively supported, but is light, gives you great freedom, and contains a nice, solid webserver that can be replaced easily with httpd.</li> <li>Django includes its own ORM, which is nice enough; there's a standalone one for Python, though, which is even nicer: <a href="http://www.sqlalchemy.org" rel="nofollow">SQL Alchemy</a></li> <li>As far as a testing library goes, <a href="http://pyunit.sourceforge.net" rel="nofollow">pyunit</a> seems to me to be the obvious choice</li> </ul> <p>Good luck, and welcome to a really fun language!</p> <p>EDIT summary: I originally recommended <a href="http://karrigell.sourceforge.net" rel="nofollow">Karrigell</a>, but can't any more: since the 3.0 release, it's been continuously broken, and the community is not large enough to solve the problems. <a href="http://www.cherrypy.org/" rel="nofollow">CherryPy</a> is a good substitute if you like a light, simple framework that doesn't get in your way, so I've changed the above to suggest it instead.</p>
5
2009-06-06T14:04:25Z
[ "python", "windows", "development-environment" ]
I need a beginners guide to setting up windows for python development
959,479
<p>I currently work with .NET exclusively and would like to have a go at python. To this end I need to set up a python development environment. I guide to this would be handy. I guess I would be doing web development so will need a web server and probably a database. I also need pointers to popular ORM's, an MVC framework, and a testing library.</p> <p>One of my main criteria with all this is that I want to understand how it works, and I want it to be as isolated as possible. This is important as i am wary of polluting what is a working .NET environment with 3rd party web and database servers. I am perfectly happy using SQLite to start with if this is possible.</p> <p>If I get on well with this I am also likely to want to set up automated build and ci server (On a virtual machine, probably ubuntu). Any suggestions for these would be useful.</p> <p>My ultimate aim if i like python is to have similar sorts of tools that i have available with .NET and to really understand the build and deployment of it all. To start with I will settle for a simple development environment that is as isolated as possible and will be easy to remove if I don't like it. I don't want to use IronPython as I want the full experience of developing a python solution using the tools and frameworks that are generally used. </p>
9
2009-06-06T11:08:51Z
959,808
<p>You should install python 2.4, python 2.5, python 2.6 and python 3.0, and add to your path the one you use more often (Add c:\Pythonxx\ and c:\Pythonxx\Scripts).</p> <p>For every python 2.x, install easy_install; Download <a href="http://peak.telecommunity.com/dist/ez%5Fsetup.py" rel="nofollow">ez_setup.py</a> and then from the cmd:</p> <pre><code>c:\Python2x\python.exe x:\path\to\ez_setup.py c:\Python2x\Scripts\easy_install virtualenv </code></pre> <p>Then each time you start a new project create a new virtual environment to isolate the specific package you needs for your project:</p> <pre><code>mkdir &lt;project name&gt; cd &lt;project name&gt; c:\Python2x\Scripts\virtualenv --no-site-packages .\v </code></pre> <p>It creates a copy of python and its libraries in .v\Scripts and .\v\Lib. Every third party packages you install in that environment will be put into .\v\Lib\site-packages. The -no-site-packages don't give access to the global site package, so you can be sure all your dependencies are in .\v\Lib\site-packages.</p> <p>To activate the virtual environment:</p> <pre><code>.\v\Scripts\activate </code></pre> <p>For the frameworks, there are many. Django is great and very well documented but you should probably look at Pylons first for its documentions on unicode, packaging, deployment and testing, and for its better WSGI support.</p> <p>For the IDE, Python comes with IDLE which is enough for learning, however you might want to look at Eclipse+PyDev, Komodo or Wingware Python IDE. Netbean 6.5 has beta support for python that looks promising (See <a href="http://www.ninjacipher.com/2009/05/01/top-5-django-ides/" rel="nofollow">top 5 python IDE</a>).</p> <p>For the webserver, you don't need any; Python has its own and all web framework come with their own. You might want to install MySql or ProgreSql; it's often better to develop on the same DB you will use for production.</p> <p>Also, when you have learnt Python, look at <a href="http://www.apress.com/book/view/9781590599815" rel="nofollow">Foundations of Agile Python Development</a> or <a href="http://www.packtpub.com/expert-python-programming/book" rel="nofollow">Expert Python Programming</a>.</p>
3
2009-06-06T14:34:09Z
[ "python", "windows", "development-environment" ]
I need a beginners guide to setting up windows for python development
959,479
<p>I currently work with .NET exclusively and would like to have a go at python. To this end I need to set up a python development environment. I guide to this would be handy. I guess I would be doing web development so will need a web server and probably a database. I also need pointers to popular ORM's, an MVC framework, and a testing library.</p> <p>One of my main criteria with all this is that I want to understand how it works, and I want it to be as isolated as possible. This is important as i am wary of polluting what is a working .NET environment with 3rd party web and database servers. I am perfectly happy using SQLite to start with if this is possible.</p> <p>If I get on well with this I am also likely to want to set up automated build and ci server (On a virtual machine, probably ubuntu). Any suggestions for these would be useful.</p> <p>My ultimate aim if i like python is to have similar sorts of tools that i have available with .NET and to really understand the build and deployment of it all. To start with I will settle for a simple development environment that is as isolated as possible and will be easy to remove if I don't like it. I don't want to use IronPython as I want the full experience of developing a python solution using the tools and frameworks that are generally used. </p>
9
2009-06-06T11:08:51Z
959,891
<p>Python has build in SQL like database and web server, so you wouldn't need to install any third party apps. Remember Python comes with batteries included.</p>
0
2009-06-06T15:08:22Z
[ "python", "windows", "development-environment" ]
I need a beginners guide to setting up windows for python development
959,479
<p>I currently work with .NET exclusively and would like to have a go at python. To this end I need to set up a python development environment. I guide to this would be handy. I guess I would be doing web development so will need a web server and probably a database. I also need pointers to popular ORM's, an MVC framework, and a testing library.</p> <p>One of my main criteria with all this is that I want to understand how it works, and I want it to be as isolated as possible. This is important as i am wary of polluting what is a working .NET environment with 3rd party web and database servers. I am perfectly happy using SQLite to start with if this is possible.</p> <p>If I get on well with this I am also likely to want to set up automated build and ci server (On a virtual machine, probably ubuntu). Any suggestions for these would be useful.</p> <p>My ultimate aim if i like python is to have similar sorts of tools that i have available with .NET and to really understand the build and deployment of it all. To start with I will settle for a simple development environment that is as isolated as possible and will be easy to remove if I don't like it. I don't want to use IronPython as I want the full experience of developing a python solution using the tools and frameworks that are generally used. </p>
9
2009-06-06T11:08:51Z
959,988
<p>Environment?</p> <p>Here is the simplest solution:</p> <ul> <li><p>Install <a href="http://www.activestate.com/activepython/" rel="nofollow">Active Python 2.6</a>. Its the Python itself, but comes with some extra handy useful stuff, like DiveintoPython chm.</p></li> <li><p>Use <a href="http://www.activestate.com/komodo%5Fedit/" rel="nofollow">Komodo Edit 5</a>. It is among the good free editor you can use for Python.</p></li> <li><p>Use <a href="http://docs.python.org/library/idle.html" rel="nofollow">IDLE</a>. Its the best simplest short snippet editor, with syntax highlighting and auto complete unmatched by most other IDEs. It comes bundled with python.</p></li> <li><p>Use <a href="http://ipython.scipy.org/moin/" rel="nofollow">Ipython</a>. Its a shell that does syntax highlighting and auto complete, bash functions, pretty print, logging, history and many such things.</p></li> <li><p>Install <a href="http://google.com/q=easy%5Finstall" rel="nofollow">easy_install</a> and/or pip for installing various 3rd party apps easily.</p></li> </ul> <p>Coming from Visual Studio and .Net it will sound a lot different, but its an entirely different world.</p> <p>For the framework, <a href="http://djangoproject.com" rel="nofollow">django</a> works the best. Walk thro the tutorial and you will be impressed enough. The documentation rocks. The community, you have to see for yourself, to know how wonderful it is!!</p>
1
2009-06-06T15:48:43Z
[ "python", "windows", "development-environment" ]