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
What is the Python equivalent of PHP's set_time_limit()?
2,024,644
<p>I have a python script which is freezing (I think it stalls waiting for socket data somewhere), but I am having trouble getting a backtrace because the only way to stop it is to kill the process in. There is a timeout on the socket also, but it doesn't seem to work.</p> <p>I am hoping that Python has a feature like...
0
2010-01-08T00:08:43Z
2,024,667
<p><a href="http://docs.python.org/library/signal.html?highlight=alarm#signal.alarm" rel="nofollow">signal.alarm</a> can help (on Unix platforms), but (depending on the platform) there may be uninterruptable system calls (and if I get the docs right, on Unix, PHP's set_time_limit does not count time spent in system cal...
3
2010-01-08T00:15:45Z
[ "php", "python" ]
What is the Python equivalent of PHP's set_time_limit()?
2,024,644
<p>I have a python script which is freezing (I think it stalls waiting for socket data somewhere), but I am having trouble getting a backtrace because the only way to stop it is to kill the process in. There is a timeout on the socket also, but it doesn't seem to work.</p> <p>I am hoping that Python has a feature like...
0
2010-01-08T00:08:43Z
2,024,690
<p>You could set a timeout on your sockets instead.</p> <pre><code>import socket socket.setdefaulttimeout(10) #10 seconds </code></pre> <p>Do that at the start of your program and everything making socket connections should respect it.</p>
1
2010-01-08T00:21:46Z
[ "php", "python" ]
Django | sort dict in template
2,024,660
<p>I want to print out a dictionary, sorted by the key. Sorting the keys is easy in the view, by just putting the keys in a list and then sorting the list. How can I loop through the keys in the template and then get the value from the dictionary.</p> <pre><code>{% for company in companies %} {% for employee, depe...
7
2010-01-08T00:13:50Z
2,024,713
<p>try this: <a href="http://www.bhphp.com/blog4.php/2009/08/17/django-templates-and-dictionaries" rel="nofollow">http://www.bhphp.com/blog4.php/2009/08/17/django-templates-and-dictionaries</a></p> <p>a custom template filter will do the trick.</p> <pre><code>from django import template register = template.Library() ...
2
2010-01-08T00:32:52Z
[ "python", "django" ]
Django | sort dict in template
2,024,660
<p>I want to print out a dictionary, sorted by the key. Sorting the keys is easy in the view, by just putting the keys in a list and then sorting the list. How can I loop through the keys in the template and then get the value from the dictionary.</p> <pre><code>{% for company in companies %} {% for employee, depe...
7
2010-01-08T00:13:50Z
8,048,313
<p>create a custom filter, which is like this:</p> <pre><code>from django import template from django.utils.datastructures import SortedDict register = template.Library() @register.filter(name='sort') def listsort(value): if isinstance(value, dict): new_dict = SortedDict() key_list = sorted(value...
18
2011-11-08T09:31:12Z
[ "python", "django" ]
Django | sort dict in template
2,024,660
<p>I want to print out a dictionary, sorted by the key. Sorting the keys is easy in the view, by just putting the keys in a list and then sorting the list. How can I loop through the keys in the template and then get the value from the dictionary.</p> <pre><code>{% for company in companies %} {% for employee, depe...
7
2010-01-08T00:13:50Z
26,043,564
<p>This last solution was very useful to me too. I'm using Django 1.6.2, and it seems to be converting a dict to a list with the key as the first elemement of that list and the content as the second. So even when I pass in a dict, it treats it as a list. So I tweaked the above to look like this, and it works for me:</p...
1
2014-09-25T16:26:44Z
[ "python", "django" ]
Django | sort dict in template
2,024,660
<p>I want to print out a dictionary, sorted by the key. Sorting the keys is easy in the view, by just putting the keys in a list and then sorting the list. How can I loop through the keys in the template and then get the value from the dictionary.</p> <pre><code>{% for company in companies %} {% for employee, depe...
7
2010-01-08T00:13:50Z
37,158,431
<p>for some reasone Turikumwe's filter not worked for me (python3.4, Django 1.7), so I rewrite it to return list of tuples instead of <code>SertedDict</code> or <code>OrderedDict</code>:</p> <pre><code>@register.filter(name='sort') def listsort(value): if isinstance(value, dict): a = [] key_list = ...
0
2016-05-11T09:29:21Z
[ "python", "django" ]
What is the relationship between 'unicode' and 'encode'
2,025,041
<pre><code>print u'\xe4\xf6\xfc'.encode('utf-8') print unicode(u'\xe4\xf6\xfc') </code></pre> <p>traceback:</p> <pre><code>盲枚眉 Traceback (most recent call last): File "D:\zjm_code\a.py", line 6, in &lt;module&gt; print unicode(u'\xe4\xf6\xfc') UnicodeEncodeError: 'ascii' codec can't encode characters in p...
1
2010-01-08T02:17:50Z
2,025,092
<p>In Python 2:</p> <pre>case a: (unicode object).encode(somecodec) -> string of bytes case b: (string of bytes).decode(somecodec) -> unicode object case c: unicode(string of bytes, somecodec) -> unicode object</pre> <p>Cases b and c are identical. In each of the three cases, you can omit the codec name: then it def...
12
2010-01-08T02:34:07Z
[ "python", "unicode" ]
What is the relationship between 'unicode' and 'encode'
2,025,041
<pre><code>print u'\xe4\xf6\xfc'.encode('utf-8') print unicode(u'\xe4\xf6\xfc') </code></pre> <p>traceback:</p> <pre><code>盲枚眉 Traceback (most recent call last): File "D:\zjm_code\a.py", line 6, in &lt;module&gt; print unicode(u'\xe4\xf6\xfc') UnicodeEncodeError: 'ascii' codec can't encode characters in p...
1
2010-01-08T02:17:50Z
2,025,094
<p>This is covered in <a href="http://docs.python.org/tutorial/introduction.html#unicode-strings" rel="nofollow">the tutorial</a> and the <a href="http://docs.python.org/howto/unicode.html" rel="nofollow">unicode howto</a></p> <p>The <code>unicode</code> function converts non-unicode (by default, ascii, but it accepts...
0
2010-01-08T02:34:21Z
[ "python", "unicode" ]
What is the relationship between 'unicode' and 'encode'
2,025,041
<pre><code>print u'\xe4\xf6\xfc'.encode('utf-8') print unicode(u'\xe4\xf6\xfc') </code></pre> <p>traceback:</p> <pre><code>盲枚眉 Traceback (most recent call last): File "D:\zjm_code\a.py", line 6, in &lt;module&gt; print unicode(u'\xe4\xf6\xfc') UnicodeEncodeError: 'ascii' codec can't encode characters in p...
1
2010-01-08T02:17:50Z
2,025,112
<h3>The encoding error:</h3> <pre><code>print unicode(u'\xe4\xf6\xfc') </code></pre> <p>The <code>unicode()</code> call does nothing here, since it's parameter is already a unicode object. <code>print</code> then tries to output that unicode object, and to do so <code>print</code> wants to convert it to a string in t...
6
2010-01-08T02:37:49Z
[ "python", "unicode" ]
mobile python 2.6 distribution/development environment?
2,025,311
<p>I'm in an interesting situation. My current computer is going to go in for repairs, and in the meantime I want to get some work done on a friend's computer, but I can't and really don't want to have to set up my development environment on the new PC. Is there a way I can carry around a working Python development env...
1
2010-01-08T03:31:29Z
2,025,315
<p><a href="http://www.portablepython.com/" rel="nofollow">Portable Python</a></p>
3
2010-01-08T03:32:13Z
[ "python" ]
mobile python 2.6 distribution/development environment?
2,025,311
<p>I'm in an interesting situation. My current computer is going to go in for repairs, and in the meantime I want to get some work done on a friend's computer, but I can't and really don't want to have to set up my development environment on the new PC. Is there a way I can carry around a working Python development env...
1
2010-01-08T03:31:29Z
2,025,337
<p>you can get PortablePython as suggested, OR you can copy the whole installed Python directory, eg C:\Python26 of your old PC into your flash drive. another you can try is <a href="http://www.voidspace.org.uk/python/movpy/" rel="nofollow">Movable Python</a> and <a href="http://mdp.cti.depaul.edu/" rel="nofollow">web...
0
2010-01-08T03:38:38Z
[ "python" ]
mobile python 2.6 distribution/development environment?
2,025,311
<p>I'm in an interesting situation. My current computer is going to go in for repairs, and in the meantime I want to get some work done on a friend's computer, but I can't and really don't want to have to set up my development environment on the new PC. Is there a way I can carry around a working Python development env...
1
2010-01-08T03:31:29Z
2,025,533
<p>Another option is to set up a remote server on Slicehost or Rackspace cloud and SSH in from your friend's machine. You'll have full control over what libraries you want installed.</p>
0
2010-01-08T04:39:07Z
[ "python" ]
Is Python a weakly typed language as variables can switch types?
2,025,353
<p>The way I understand it, the following is allowed in PHP because it's a weakly-typed language.</p> <pre><code>$var = 'Hello'; $var = 5; </code></pre> <p>I just installed a Windows version of Python 2.6 and I was expecting it NOT to let me change type just like that, but the Python equivalent of the above code work...
10
2010-01-08T03:43:07Z
2,025,361
<p>Your example demonstrates <em>dynamic</em> typing, not weak typing. Dynamic typing generally means that the type of data an object can store is mutable; any target may hold a binding to any kind of object. Contrast that with, say, C#, which is statically typed [*].</p> <pre><code>int i = 5; // Okay. i = "5"; // I...
38
2010-01-08T03:45:20Z
[ "python", "strong-typing", "weak-typing" ]
Is Python a weakly typed language as variables can switch types?
2,025,353
<p>The way I understand it, the following is allowed in PHP because it's a weakly-typed language.</p> <pre><code>$var = 'Hello'; $var = 5; </code></pre> <p>I just installed a Windows version of Python 2.6 and I was expecting it NOT to let me change type just like that, but the Python equivalent of the above code work...
10
2010-01-08T03:43:07Z
2,025,362
<p>Yes. That is not strong/weak typing, that is static/dynamic typing. Weak typing allows things such as <code>5 + '5'</code> to equal 10.</p>
1
2010-01-08T03:45:23Z
[ "python", "strong-typing", "weak-typing" ]
Is Python a weakly typed language as variables can switch types?
2,025,353
<p>The way I understand it, the following is allowed in PHP because it's a weakly-typed language.</p> <pre><code>$var = 'Hello'; $var = 5; </code></pre> <p>I just installed a Windows version of Python 2.6 and I was expecting it NOT to let me change type just like that, but the Python equivalent of the above code work...
10
2010-01-08T03:43:07Z
2,025,399
<p>There's no real definition of weak typing or strong typing. Its all about implicit type conversions and has nothing to do with static/dynamic typing.</p> <p>A statically typed language like Java <strong>can</strong> be weakly typed (not that is it), and a dynamically typed language like PHP <strong>can</strong> be ...
4
2010-01-08T03:56:41Z
[ "python", "strong-typing", "weak-typing" ]
Is Python a weakly typed language as variables can switch types?
2,025,353
<p>The way I understand it, the following is allowed in PHP because it's a weakly-typed language.</p> <pre><code>$var = 'Hello'; $var = 5; </code></pre> <p>I just installed a Windows version of Python 2.6 and I was expecting it NOT to let me change type just like that, but the Python equivalent of the above code work...
10
2010-01-08T03:43:07Z
2,025,521
<p>One addition the the first answer: It's a tad more complicated because in python the + operator is overloaded meaning it would both add (math) and concatenate (glue two strings). In the php example</p> <pre><code>$i = 1 + "1" // $i == 2 </code></pre> <p>the plus adds (math) because the . (dot) is used for concaten...
5
2010-01-08T04:35:41Z
[ "python", "strong-typing", "weak-typing" ]
Replacing text in Python
2,025,513
<p>I've been looking at the re documentation and at other questions but I keep running into trouble with regex. </p> <p>I need to take what ever is in the [tag] off of the string.</p> <pre><code>string = "Article Name [Tag Name]" #and I want to go to string = "Article Name" </code></pre> <p>I'd really appreciate it ...
2
2010-01-08T04:31:27Z
2,025,525
<pre><code>re.sub("\s*\[.*?\]", "", string) </code></pre>
2
2010-01-08T04:36:03Z
[ "python", "regex" ]
Replacing text in Python
2,025,513
<p>I've been looking at the re documentation and at other questions but I keep running into trouble with regex. </p> <p>I need to take what ever is in the [tag] off of the string.</p> <pre><code>string = "Article Name [Tag Name]" #and I want to go to string = "Article Name" </code></pre> <p>I'd really appreciate it ...
2
2010-01-08T04:31:27Z
2,025,527
<pre><code>re.sub(r"(.*) \[.*\]", r"\1", string) </code></pre> <p>This will only remove the tag if it's at the end of the string.</p>
0
2010-01-08T04:36:24Z
[ "python", "regex" ]
Replacing text in Python
2,025,513
<p>I've been looking at the re documentation and at other questions but I keep running into trouble with regex. </p> <p>I need to take what ever is in the [tag] off of the string.</p> <pre><code>string = "Article Name [Tag Name]" #and I want to go to string = "Article Name" </code></pre> <p>I'd really appreciate it ...
2
2010-01-08T04:31:27Z
2,025,542
<p>If you are sure [Tag Name] is always come after Article Name, you could do this without regex.</p> <pre><code>&gt;&gt;&gt; string="Article Name [Tag Name]" &gt;&gt;&gt; string[:string.find(" [")] 'Article Name' </code></pre> <p>or with .partition</p> <pre><code>&gt;&gt;&gt; string.partition(" [")[0] 'Article Name...
1
2010-01-08T04:42:09Z
[ "python", "regex" ]
Replacing text in Python
2,025,513
<p>I've been looking at the re documentation and at other questions but I keep running into trouble with regex. </p> <p>I need to take what ever is in the [tag] off of the string.</p> <pre><code>string = "Article Name [Tag Name]" #and I want to go to string = "Article Name" </code></pre> <p>I'd really appreciate it ...
2
2010-01-08T04:31:27Z
2,025,544
<p>This does not use regex so if that is a requirement this is not an answer but you could do this:</p> <pre><code> string = string.split('[')[0].strip() </code></pre>
1
2010-01-08T04:42:25Z
[ "python", "regex" ]
Replacing text in Python
2,025,513
<p>I've been looking at the re documentation and at other questions but I keep running into trouble with regex. </p> <p>I need to take what ever is in the [tag] off of the string.</p> <pre><code>string = "Article Name [Tag Name]" #and I want to go to string = "Article Name" </code></pre> <p>I'd really appreciate it ...
2
2010-01-08T04:31:27Z
2,025,555
<p>Even better without regex:</p> <pre><code>txt = "Article Name [Tag Name]" if txt.rfind('[') and txt.rfind(']') &gt; txt.rfind('['): txt = txt[:txt.rfind('[')] if txt[-1] == ' ': txt = txt[:-1] </code></pre>
0
2010-01-08T04:44:31Z
[ "python", "regex" ]
Replacing text in Python
2,025,513
<p>I've been looking at the re documentation and at other questions but I keep running into trouble with regex. </p> <p>I need to take what ever is in the [tag] off of the string.</p> <pre><code>string = "Article Name [Tag Name]" #and I want to go to string = "Article Name" </code></pre> <p>I'd really appreciate it ...
2
2010-01-08T04:31:27Z
2,025,823
<p>here's one for multiple instances of [] tags</p> <pre><code>&gt;&gt;&gt; string = "Article Name [Tag Name] blah blah [tag name2] blah blah [tag name3]" &gt;&gt;&gt; for i in string.split("]"): ... print i[ : i.find("[") ] ... Article Name blah blah blah blah </code></pre>
0
2010-01-08T06:00:33Z
[ "python", "regex" ]
Inherit docstrings in Python class inheritance
2,025,562
<p>I'm trying to do some class inheritance in Python. I'd like each class and inherited class to have good docstrings. So I think for the inherited class, I'd like it to:</p> <ul> <li>inherit the base class docstring</li> <li>also append relevant extra documentation to the docstring</li> </ul> <p>Is there some "best ...
53
2010-01-08T04:45:11Z
2,025,581
<p>You're not the only one! There was a discussion on <code>comp.lang.python</code> about this a while ago, and a recipe was created. Check it out <strong><a href="http://code.activestate.com/recipes/576862/">here</a></strong>.</p> <pre><code>""" doc_inherit decorator Usage: class Foo(object): def foo(self): ...
26
2010-01-08T04:51:35Z
[ "python", "inheritance", "documentation" ]
Inherit docstrings in Python class inheritance
2,025,562
<p>I'm trying to do some class inheritance in Python. I'd like each class and inherited class to have good docstrings. So I think for the inherited class, I'd like it to:</p> <ul> <li>inherit the base class docstring</li> <li>also append relevant extra documentation to the docstring</li> </ul> <p>Is there some "best ...
53
2010-01-08T04:45:11Z
2,025,599
<p>You can concatenate the docstrings easily:</p> <pre><code>class Foo(object): """ Foo Class. This class foos around. """ pass class Bar(Foo): """ Bar class, children of Foo Use this when you want to Bar around. parent: """ __doc__ += Foo.__doc__ pass </code></pre> <...
17
2010-01-08T04:55:23Z
[ "python", "inheritance", "documentation" ]
Inherit docstrings in Python class inheritance
2,025,562
<p>I'm trying to do some class inheritance in Python. I'd like each class and inherited class to have good docstrings. So I think for the inherited class, I'd like it to:</p> <ul> <li>inherit the base class docstring</li> <li>also append relevant extra documentation to the docstring</li> </ul> <p>Is there some "best ...
53
2010-01-08T04:45:11Z
2,025,612
<p>Not particularly elegant, but simple and direct:</p> <pre><code>class X(object): """This class has a method foo().""" def foo(): pass class Y(X): __doc__ = X.__doc__ + ' Also bar().' def bar(): pass </code></pre> <p>Now:</p> <pre><code>&gt;&gt;&gt; print Y.__doc__ This class has a method foo(). Also bar(...
3
2010-01-08T04:59:24Z
[ "python", "inheritance", "documentation" ]
Inherit docstrings in Python class inheritance
2,025,562
<p>I'm trying to do some class inheritance in Python. I'd like each class and inherited class to have good docstrings. So I think for the inherited class, I'd like it to:</p> <ul> <li>inherit the base class docstring</li> <li>also append relevant extra documentation to the docstring</li> </ul> <p>Is there some "best ...
53
2010-01-08T04:45:11Z
17,353,586
<p>A mixed stile that can preserve both the inherited docstring syntax and the preferred ordering can be:</p> <pre><code>class X(object): """This class has a method foo().""" def foo(): pass class Y(X): """ Also bar().""" __doc__ = X.__doc__ + __doc__ def bar(): pass </code></pre> <p>With the same output a...
2
2013-06-27T21:31:51Z
[ "python", "inheritance", "documentation" ]
MasterPage like concept in python
2,025,565
<p>We are developing a web based application in python on google app engine platform. I have different pages in web site. What I want is to have a master page like functionality like we have in asp.net where I have just on template and all other pages will use that. How can I do this? I am a beginner in python</p>
7
2010-01-08T04:46:00Z
2,025,647
<p>If you're using Django (or at least Django templates), <a href="http://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance">Django template inheritance</a> may be what you're looking for.</p>
11
2010-01-08T05:11:24Z
[ "python", "google-app-engine", "master-pages" ]
MasterPage like concept in python
2,025,565
<p>We are developing a web based application in python on google app engine platform. I have different pages in web site. What I want is to have a master page like functionality like we have in asp.net where I have just on template and all other pages will use that. How can I do this? I am a beginner in python</p>
7
2010-01-08T04:46:00Z
36,234,263
<p>I think you are exactly looking for "template extending".</p> <ol> <li><p>Create base/master html file in "templates" folder.</p> <p>This will be base/master file where all theme css,js , html layout tags exists.</p></li> <li><p>Add place holders for child html "content" in above base/master html</p> <p><code>{% ...
1
2016-03-26T10:33:01Z
[ "python", "google-app-engine", "master-pages" ]
conditional skip in python if
2,025,701
<p>i am trying for something like this</p> <pre><code>def scanthefile(): x = 11 if x &gt; 5 """ i want to come out of if and go to end of scanfile """ print x return info </code></pre> <p><strong>update:</strong></p> <p>if have to check for the content size of a file. and if the content...
0
2010-01-08T05:23:24Z
2,025,715
<p>If I understand your question, and I'm really unsure I do, you can just de-indent:</p> <pre><code>x = 11 if x &gt; 5: pass # Your code goes here. print x </code></pre>
1
2010-01-08T05:26:12Z
[ "python", "if-statement" ]
conditional skip in python if
2,025,701
<p>i am trying for something like this</p> <pre><code>def scanthefile(): x = 11 if x &gt; 5 """ i want to come out of if and go to end of scanfile """ print x return info </code></pre> <p><strong>update:</strong></p> <p>if have to check for the content size of a file. and if the content...
0
2010-01-08T05:23:24Z
2,025,728
<p>By "go to the end of file", do you mean "seek to the end of file"? Then:</p> <pre><code>import os ... if x &gt; 5: thefile.seek(0, os.SEEK_END) </code></pre> <p>If you mean something completely different, you'd better clarify!</p>
2
2010-01-08T05:30:34Z
[ "python", "if-statement" ]
conditional skip in python if
2,025,701
<p>i am trying for something like this</p> <pre><code>def scanthefile(): x = 11 if x &gt; 5 """ i want to come out of if and go to end of scanfile """ print x return info </code></pre> <p><strong>update:</strong></p> <p>if have to check for the content size of a file. and if the content...
0
2010-01-08T05:23:24Z
2,025,760
<p>OK, so to answer your update:</p> <pre><code>import os fn = 'somefile.txt' thefile = open(fn, 'r') # The next line check the size of the file. Replace "stat(fn).st_size" with your own code if you want. if stat(fn).st_size &gt; 500: thefile.seek(0, os.SEEK_END) # you are now at the end of the file if the size ...
2
2010-01-08T05:39:31Z
[ "python", "if-statement" ]
conditional skip in python if
2,025,701
<p>i am trying for something like this</p> <pre><code>def scanthefile(): x = 11 if x &gt; 5 """ i want to come out of if and go to end of scanfile """ print x return info </code></pre> <p><strong>update:</strong></p> <p>if have to check for the content size of a file. and if the content...
0
2010-01-08T05:23:24Z
2,027,378
<p>The way I understand the question is that you want to break out of an <strong>if-statement</strong>, which you can't.</p> <p>You can however replace it with a <strong>while loop</strong>:</p> <pre><code>def scanthefile(): x = 11 while x &gt; 5: # do something here... if CONTENTSIZE &gt; 5...
0
2010-01-08T12:01:05Z
[ "python", "if-statement" ]
How to become a great open source programmer of python?
2,025,799
<p>I'm a C# programmer of web applications.</p> <p>Weeks ago, I asked a question on stackoverflow about <a href="http://stackoverflow.com/questions/1965472/what-should-a-software-engineer-web-start-by-learning-erlang-haskell-python">What should a software engineer (web) start by learning - Erlang, Haskell, Python, C++...
1
2010-01-08T05:53:46Z
2,025,809
<p>Start coding! Seriously, create some sample apps. If you run into pain points, that's where you'll learn. When you're done one, then read best practices books to learn how you could have done better. Otherwise you're not learning, you're just following a recipe.</p>
1
2010-01-08T05:56:40Z
[ "python", "c" ]
How to become a great open source programmer of python?
2,025,799
<p>I'm a C# programmer of web applications.</p> <p>Weeks ago, I asked a question on stackoverflow about <a href="http://stackoverflow.com/questions/1965472/what-should-a-software-engineer-web-start-by-learning-erlang-haskell-python">What should a software engineer (web) start by learning - Erlang, Haskell, Python, C++...
1
2010-01-08T05:53:46Z
2,025,829
<p>Read lots of code. Develop your own coding style, but work on a lot of projects so that:</p> <p>a) your style can inherit the best parts of theirs</p> <p>b) you won't get into the bad habit of always doing things the way you've first learned (as python is constantly changing, and so the 'best' idiom has a habit of...
0
2010-01-08T06:01:39Z
[ "python", "c" ]
How to become a great open source programmer of python?
2,025,799
<p>I'm a C# programmer of web applications.</p> <p>Weeks ago, I asked a question on stackoverflow about <a href="http://stackoverflow.com/questions/1965472/what-should-a-software-engineer-web-start-by-learning-erlang-haskell-python">What should a software engineer (web) start by learning - Erlang, Haskell, Python, C++...
1
2010-01-08T05:53:46Z
2,025,883
<p>Wow, plenty of questions you ask. Let me try to address them...</p> <blockquote> <p>Why all the good names backend their process with C and use Python for script? Doesn't Python good enough to be used for backend process?</p> </blockquote> <p>I'm not sure what you mean. Python is used a lot in back-end w...
5
2010-01-08T06:25:56Z
[ "python", "c" ]
How to become a great open source programmer of python?
2,025,799
<p>I'm a C# programmer of web applications.</p> <p>Weeks ago, I asked a question on stackoverflow about <a href="http://stackoverflow.com/questions/1965472/what-should-a-software-engineer-web-start-by-learning-erlang-haskell-python">What should a software engineer (web) start by learning - Erlang, Haskell, Python, C++...
1
2010-01-08T05:53:46Z
2,025,892
<p>There are two major reasons to write C code instead of Python: speed, and glue.</p> <p>Python is significantly slower than C. Most of the time, this won't matter at all, but sometimes it does. If you were to write a Fourier Transform function in pure Python, you would not be happy with the speed; so the SciPy guy...
0
2010-01-08T06:28:05Z
[ "python", "c" ]
Popen always run, ignoring the if
2,025,885
<p>I want that when I respond other thing diferent that yes, the subprocess don't run. </p> <pre><code>r = raw_input('\nDo you want play the video?\n\nY:Yes N:No\n\n') if r == "Y" or "y" or "yes" or"yep" or"yeah": message("Playing Video") subprocess.Popen(playvid) else: pass </code></pre>
1
2010-01-08T06:26:12Z
2,025,897
<p>change this</p> <pre><code>if r == "Y" or "y" or "yes" or"yep" or"yeah": </code></pre> <p>to </p> <pre><code>if r in ["Y","y","yes","yep","yeah"] : </code></pre> <p>or change your response to lower case</p> <pre><code>r = raw_input('\nDo you want play the video?\n\nY:Yes N:No\n\n').lower() if r in ["y","yes","...
1
2010-01-08T06:29:37Z
[ "python" ]
Popen always run, ignoring the if
2,025,885
<p>I want that when I respond other thing diferent that yes, the subprocess don't run. </p> <pre><code>r = raw_input('\nDo you want play the video?\n\nY:Yes N:No\n\n') if r == "Y" or "y" or "yes" or"yep" or"yeah": message("Playing Video") subprocess.Popen(playvid) else: pass </code></pre>
1
2010-01-08T06:26:12Z
2,025,902
<p>I'm not sure if I fully understand your question, but I believe the issue is your syntax in this line:</p> <pre><code>if r == "Y" or "y" or "yes" or"yep" or"yeah": </code></pre> <p>You are testing the truth of "Y", "y", etc, which all evaluate to "true". Put all of the values in a sequence and do:</p> <pre><code>...
1
2010-01-08T06:31:38Z
[ "python" ]
See What Line a Function Was Called From in Python Decorator
2,025,941
<p>Given something like this:</p> <pre><code>@my_decorator my_function(some, args) </code></pre> <p>Is it possible for my_decorator to discover the file and line number my_function was called from?</p> <p>Thanks</p>
2
2010-01-08T06:43:22Z
2,025,959
<p><code>traceback.extract_stack()</code> will allow you to examine the current stack frame.</p>
3
2010-01-08T06:48:13Z
[ "python", "decorator", "inspect" ]
How do you ask gstreamer if a file can be played?
2,025,964
<p>I'm trying to write a simple command line audio player using the Python Gstreamer bindings. Is there a function in the gstreamer API that determines in advance whether or not a particular file (URI) can be decoded and played by the currently installed set of codecs?</p>
1
2010-01-08T06:49:42Z
2,026,830
<p>I guess you can try to play it and see if that raises any error - in fact, there's no way to know the set of codecs necessary without opening the file. Some distributions even have hooks in place that ask the user to download the right codec when you start playing something.</p>
0
2010-01-08T10:14:04Z
[ "python", "uri", "decode", "gstreamer", "codec" ]
What is the proper way to use str.decode and unicode.encode?
2,025,969
<p>What is the proper way to use <code>str.decode</code> and <code>unicode.encode</code>?</p> <p>Eg.</p> <pre><code>print str.decode print unicode.encode </code></pre>
-4
2010-01-08T06:51:09Z
2,025,987
<pre><code>print 'あ'.decode('utf-8') print repr(u'あ'.encode('shift-jis')) </code></pre>
0
2010-01-08T06:55:46Z
[ "python" ]
What is the proper way to use str.decode and unicode.encode?
2,025,969
<p>What is the proper way to use <code>str.decode</code> and <code>unicode.encode</code>?</p> <p>Eg.</p> <pre><code>print str.decode print unicode.encode </code></pre>
-4
2010-01-08T06:51:09Z
2,026,073
<p>Ignacio's example is correct but depends on your console being able to display Unicode characters, which on Windows it usually can't. Here's the same thing with only safe string escapes (reprs):</p> <pre><code>&gt;&gt;&gt; '\xe3\x81\x82'.decode('utf-8') # three top-bit-set bytes, representing one character u'\u3...
1
2010-01-08T07:22:50Z
[ "python" ]
What is the proper way to use str.decode and unicode.encode?
2,025,969
<p>What is the proper way to use <code>str.decode</code> and <code>unicode.encode</code>?</p> <p>Eg.</p> <pre><code>print str.decode print unicode.encode </code></pre>
-4
2010-01-08T06:51:09Z
2,046,160
<pre><code>&gt;&gt;&gt; unicode.encode(u"abcd","utf8") 'abcd' #unicode string u"abcd" got encoded to UTF-8 encoded string "abcd" &gt;&gt;&gt; str.decode("abcd","utf8") u'abcd' #UTF-8 string "abcd" got decoded to python's unicode object u"abcd" &gt;&gt;&gt; </code></pre>
0
2010-01-12T01:50:24Z
[ "python" ]
Relationship between string module and str
2,026,038
<p>What is the difference or relationship between <em>str</em> and <em>string</em>?</p> <pre><code>import string print str print string </code></pre>
10
2010-01-08T07:12:57Z
2,026,050
<p><a href="http://docs.python.org/3.1/library/functions.html#str"><code>str</code></a> is a <a href="http://docs.python.org/3.1/library/functions.html">built-in function</a> (actually a <a href="http://docs.python.org/tutorial/classes.html">class</a>) which converts its argument to a string. <a href="http://docs.pytho...
14
2010-01-08T07:16:31Z
[ "python" ]
Relationship between string module and str
2,026,038
<p>What is the difference or relationship between <em>str</em> and <em>string</em>?</p> <pre><code>import string print str print string </code></pre>
10
2010-01-08T07:12:57Z
2,026,051
<p>"string" is a module that provides string handling functions, str is a built-in function that converts an object to a string representation. No relationship between the two.</p>
0
2010-01-08T07:16:50Z
[ "python" ]
Relationship between string module and str
2,026,038
<p>What is the difference or relationship between <em>str</em> and <em>string</em>?</p> <pre><code>import string print str print string </code></pre>
10
2010-01-08T07:12:57Z
2,026,151
<p>There is some overlap between the string module and the str type, mainly for historical reasons. In early versions of Python str objects did not have methods, so all string manipulation was done with functions from the string module. When methods were added to the str type (in Python 1.5?) the functions were left ...
1
2010-01-08T07:46:51Z
[ "python" ]
Relationship between string module and str
2,026,038
<p>What is the difference or relationship between <em>str</em> and <em>string</em>?</p> <pre><code>import string print str print string </code></pre>
10
2010-01-08T07:12:57Z
2,026,483
<p>Like Stephan202 said: str is a built in function which is just used to convert item into string. It has also many useful methods. For instance:</p> <pre><code>&gt;&gt;&gt; str(100) '100' # converts integer into string. &gt;&gt;&gt; str.lower('foobar') 'FOOBAR' </code></pre> <p>Now let's talk about String.-- It a ...
4
2010-01-08T09:07:49Z
[ "python" ]
Strategies or support for making parts of a Twisted application reloadable?
2,026,091
<p>I've written a specialized JSON-RPC server and just started working my way up into the application logic and finding it is a tad annoying to constantly having to stop/restart the server to make certain changes.</p> <p>Previously I had a handler that ran in intervals to compare module modified time stamps with the p...
3
2010-01-08T07:28:12Z
2,026,161
<p>You could write something similar to paster's reloader, that would work like this:</p> <ol> <li>start your main function, and before importing / using any twisted code, fork/spawn a subprocess.</li> <li>In the subprocess, run your twisted application.</li> <li>In the main process, run your code which checks for cha...
1
2010-01-08T07:49:08Z
[ "python", "twisted" ]
Strategies or support for making parts of a Twisted application reloadable?
2,026,091
<p>I've written a specialized JSON-RPC server and just started working my way up into the application logic and finding it is a tad annoying to constantly having to stop/restart the server to make certain changes.</p> <p>Previously I had a handler that ran in intervals to compare module modified time stamps with the p...
3
2010-01-08T07:28:12Z
2,026,620
<p>Shipped with Twisted is the <a href="http://twistedmatrix.com/documents/current/api/twisted.python.rebuild.html" rel="nofollow">twisted.python.rebuild</a> module, so that is probably a good place to start. </p> <p>Also see this SO question: <a href="http://stackoverflow.com/questions/126787/checking-for-code-chang...
2
2010-01-08T09:37:25Z
[ "python", "twisted" ]
How to create Python egg file
2,026,395
<p>I have questions about egg files in Python.</p> <p>I have much Python code organized by package and I'm trying to create egg files. I'm following <a href="http://peak.telecommunity.com/DevCenter/PythonEggs#building-eggs">instructions</a>, but they are very common.</p> <p>According to that, it seems I need to have ...
71
2010-01-08T08:46:51Z
2,027,033
<p>You are reading the wrong documentation. You want this: <a href="http://peak.telecommunity.com/DevCenter/setuptools">http://peak.telecommunity.com/DevCenter/setuptools</a></p> <ol> <li><p>Creating setup.py is covered in the distutils documentation in Python's standard library documentation <a href="http://docs.pyth...
62
2010-01-08T10:54:42Z
[ "python", "packaging", "egg" ]
How to create Python egg file
2,026,395
<p>I have questions about egg files in Python.</p> <p>I have much Python code organized by package and I'm trying to create egg files. I'm following <a href="http://peak.telecommunity.com/DevCenter/PythonEggs#building-eggs">instructions</a>, but they are very common.</p> <p>According to that, it seems I need to have ...
71
2010-01-08T08:46:51Z
7,930,975
<p>For #4, the closest thing to starting java with a jar file for your app is a new feature in Python 2.6, <a href="http://docs.python.org/whatsnew/2.6.html#other-language-changes">executable zip files and directories</a>.</p> <pre><code>python myapp.zip </code></pre> <p>Where myapp.zip is a zip containing a <code>__...
26
2011-10-28T14:55:58Z
[ "python", "packaging", "egg" ]
How to create Python egg file
2,026,395
<p>I have questions about egg files in Python.</p> <p>I have much Python code organized by package and I'm trying to create egg files. I'm following <a href="http://peak.telecommunity.com/DevCenter/PythonEggs#building-eggs">instructions</a>, but they are very common.</p> <p>According to that, it seems I need to have ...
71
2010-01-08T08:46:51Z
28,337,029
<p>I think you should use <a href="http://pythonwheels.com/">python wheels</a> for distribution instead of egg now.</p> <blockquote> <p>Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.</p> </blockquote>
6
2015-02-05T05:49:17Z
[ "python", "packaging", "egg" ]
Python Cherrypy 404 Error Handling
2,026,414
<p>I have a web server that has all of the configurations set in the code, but I want to be able to handle all page 404 errors. How would I go about doing this in Python?</p>
5
2010-01-08T08:50:55Z
2,026,455
<p>Make a default handler in the root.</p> <pre><code>class Root: def index(self): return "Hello!" index.exposed = True def default(self, attr='abc'): return "Page not Found!" default.exposed = True </code></pre>
5
2010-01-08T08:58:21Z
[ "python", "cherrypy" ]
Python Cherrypy 404 Error Handling
2,026,414
<p>I have a web server that has all of the configurations set in the code, but I want to be able to handle all page 404 errors. How would I go about doing this in Python?</p>
5
2010-01-08T08:50:55Z
2,029,218
<p>See also <a href="http://www.cherrypy.org/wiki/ErrorsAndExceptions#AnticipatedHTTPresponses">http://www.cherrypy.org/wiki/ErrorsAndExceptions#AnticipatedHTTPresponses</a> if you want more traditional replacement of 4xx and 5xx output.</p>
9
2010-01-08T17:01:06Z
[ "python", "cherrypy" ]
Is it possible to tell a python script to stop at some point and give you the hand interactively, for example with ipython?
2,026,447
<p>Suppose I have a script that does a lot of stuff, and doesn't work well somewhere near the end. I'd love to be able to add a <code>start_ipython()</code> function at that point, which would stop the script at this point, and let me inspect variables and so on with ipython. How can I do this?</p>
5
2010-01-08T08:57:20Z
2,026,503
<p>Easiest way is to use the built-in debugger. At the point you want execution to stop, just do:</p> <pre><code>import pdb; pdb.set_trace() </code></pre> <p>and you'll be dumped into the pdb shell, which allows you to inspect variables and change them.</p> <p>There is also an external <code>ipdb</code> package whic...
6
2010-01-08T09:13:15Z
[ "python" ]
Is it possible to tell a python script to stop at some point and give you the hand interactively, for example with ipython?
2,026,447
<p>Suppose I have a script that does a lot of stuff, and doesn't work well somewhere near the end. I'd love to be able to add a <code>start_ipython()</code> function at that point, which would stop the script at this point, and let me inspect variables and so on with ipython. How can I do this?</p>
5
2010-01-08T08:57:20Z
2,026,554
<p>Note that this has changed in IPython-0.11. Instead of what is described below, simply use the following import:</p> <pre><code>from IPython import embed as shell </code></pre> <p>The answer below works for IPython versions prior to 0.11.</p> <hr> <p>In the region where you want to drop into ipython, define thi...
15
2010-01-08T09:22:41Z
[ "python" ]
Work with Postgres/PostGIS View in SQLAlchemy
2,026,475
<p>Two questions:</p> <ul> <li><p>i want to generate a View in my PostGIS-DB. How do i add this View to my geometry_columns Table?</p></li> <li><p>What i have to do, to use a View with SQLAlchemy? Is there a difference between a Table and View to SQLAlchemy or could i use the same way to use a View as i do to use a Ta...
2
2010-01-08T09:05:48Z
2,027,143
<p>Table objects in SQLAlchemy have two roles. They can be used to issue DDL commands to create the table in the database. But their main purpose is to describe the columns and types of tabular data that can be selected from and inserted to.</p> <p>If you only want to select, then a view looks to SQLAlchemy exactly li...
4
2010-01-08T11:13:01Z
[ "python", "postgresql", "sqlalchemy", "postgis" ]
Python multiple inheritance: Whats wrong doing it dynamically?
2,026,572
<p>Based on <a href="http://stackoverflow.com/questions/2017876/why-defined-new-and-init-all-in-a-class/2017980#2017980">this answer</a>, of how <code>__new__</code> and <code>__init__</code> are supposed to work in Python,</p> <p>I wrote this code to dynamically define and create a new class and object.</p> <pre><co...
0
2010-01-08T09:27:07Z
2,026,633
<p>If your question is "How can I accomplish this" &ndash; this works:</p> <pre><code>class A(object): @classmethod def get_with_B(cls): class C(B, cls): pass return C() def foo(self): print 'foo' class B(object): def bar(self): print 'bar' a = A.get_with_B() a.foo()...
3
2010-01-08T09:40:16Z
[ "python", "multiple-inheritance" ]
Python multiple inheritance: Whats wrong doing it dynamically?
2,026,572
<p>Based on <a href="http://stackoverflow.com/questions/2017876/why-defined-new-and-init-all-in-a-class/2017980#2017980">this answer</a>, of how <code>__new__</code> and <code>__init__</code> are supposed to work in Python,</p> <p>I wrote this code to dynamically define and create a new class and object.</p> <pre><co...
0
2010-01-08T09:27:07Z
2,026,642
<p>Since there is no actual <em>question</em> in the <em>question</em>, I am going to take it literally:</p> <p><strong>Whats wrong doing it dynamically?</strong><br> Well, it is practically unreadable, extremely opaque and non-obvious to the user of your code (that includes you in a month :P).</p> <p>From my experie...
7
2010-01-08T09:41:29Z
[ "python", "multiple-inheritance" ]
Python multiple inheritance: Whats wrong doing it dynamically?
2,026,572
<p>Based on <a href="http://stackoverflow.com/questions/2017876/why-defined-new-and-init-all-in-a-class/2017980#2017980">this answer</a>, of how <code>__new__</code> and <code>__init__</code> are supposed to work in Python,</p> <p>I wrote this code to dynamically define and create a new class and object.</p> <pre><co...
0
2010-01-08T09:27:07Z
2,026,666
<p><a href="http://codepad.org/PhYOUqxc">Resolve</a> the infinite recursion:</p> <pre><code>class A(object): def __new__(cls): class C(cls, B): pass self = object.__new__(C) return self </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/questions/2026572/python-multiple-inheritance-what...
7
2010-01-08T09:44:50Z
[ "python", "multiple-inheritance" ]
Python: Get importing module's details from within imported module
2,026,788
<p>I'm writing a piece of reusable code to import where I need it, but it needs some info about what is importing it. I have a workaround that does what I want, but it's a bit ugly. Is there a better way?</p> <p>Here is a simplified version of what I'm doing.</p> <p><strong>What I want:</strong> Import a method and u...
2
2010-01-08T10:04:55Z
2,026,821
<p>That's a bad idea, because modules are cached.</p> <p>So if another module, say, <code>mod3.py</code>, also imports <code>mod2</code>, it will get the same <code>mod2</code> object of the first time. The module is not reimported.</p> <p>Maybe you imported some other module that imported <code>mod2</code> before im...
4
2010-01-08T10:11:48Z
[ "python", "django", "rest", "import" ]
Packaging Python applications with configuration files
2,026,876
<p>I'm using ConfigParser for configuring my application, and now I want to make it easily distributable, and at the same time preserve the configurability. </p> <p>I'm thinking I need a directory with configuration file templates, and some way of generating the configuration to actually use from these. Then I need a ...
9
2010-01-08T10:24:51Z
2,026,916
<p>you can use <a href="http://docs.python.org/distutils/setupscript.html#installing-additional-files"><code>data_files</code></a> option of <code>distutils</code> to install files wherever you want.</p> <p><code>data_files</code> specifies a sequence of <code>(directory, files)</code> pairs in the following way:</p> ...
7
2010-01-08T10:33:17Z
[ "python", "configuration-files", "packaging" ]
Pygame programs hanging on exit
2,027,105
<p>I'm tinkering around with pygame right now, and it seems like all the little programs that I make with it hang when I try to close them.</p> <p>Take the following code, for example:</p> <pre><code>from pygame.locals import * pygame.init() # YEEAAH! tile_file = "blue_tile.bmp" SCREEN_SIZE = (640, 480) SCREEN_DEPTH ...
8
2010-01-08T11:06:06Z
2,027,127
<p>If you are running it from IDLE, then you are missing <strong>pygame.quit()</strong>.</p> <blockquote> <p>This is caused by the IDLE python interpreter, which seems to keep the references around somehow. Make sure, you invoke pygame.quit() on exiting your application or game.</p> </blockquote> <p>See: <a href="h...
10
2010-01-08T11:09:00Z
[ "python", "pygame" ]
Pygame programs hanging on exit
2,027,105
<p>I'm tinkering around with pygame right now, and it seems like all the little programs that I make with it hang when I try to close them.</p> <p>Take the following code, for example:</p> <pre><code>from pygame.locals import * pygame.init() # YEEAAH! tile_file = "blue_tile.bmp" SCREEN_SIZE = (640, 480) SCREEN_DEPTH ...
8
2010-01-08T11:06:06Z
2,027,185
<p>Where do you exit the outer loop?</p> <pre><code> while True: # outer loop for event in pygame.event.get(): # inner loop if event.type == QUIT: break # &lt;- break inner loop </code></pre>
12
2010-01-08T11:22:04Z
[ "python", "pygame" ]
Pygame programs hanging on exit
2,027,105
<p>I'm tinkering around with pygame right now, and it seems like all the little programs that I make with it hang when I try to close them.</p> <p>Take the following code, for example:</p> <pre><code>from pygame.locals import * pygame.init() # YEEAAH! tile_file = "blue_tile.bmp" SCREEN_SIZE = (640, 480) SCREEN_DEPTH ...
8
2010-01-08T11:06:06Z
4,670,054
<p>I had a similar problem on knowing why I can't close pygame windows.. and searched.. and came across this..</p> <p>I think this explains everything.. and good idea too..</p> <p>as seen in: <a href="http://bytes.com/topic/python/answers/802028-pygame-window-not-closing-tut-not-helping" rel="nofollow">http://bytes.c...
0
2011-01-12T14:45:23Z
[ "python", "pygame" ]
Pygame programs hanging on exit
2,027,105
<p>I'm tinkering around with pygame right now, and it seems like all the little programs that I make with it hang when I try to close them.</p> <p>Take the following code, for example:</p> <pre><code>from pygame.locals import * pygame.init() # YEEAAH! tile_file = "blue_tile.bmp" SCREEN_SIZE = (640, 480) SCREEN_DEPTH ...
8
2010-01-08T11:06:06Z
10,108,973
<p>I had the same problem, but solved it by doing the following:</p> <pre><code>try: while True: for event in pygame.event.get(): if event.type==QUIT or pygame.key.get_pressed()[K_ESCAPE]: pygame.quit() break finally: pygame.quit() </code></pre>
3
2012-04-11T15:22:21Z
[ "python", "pygame" ]
Pygame programs hanging on exit
2,027,105
<p>I'm tinkering around with pygame right now, and it seems like all the little programs that I make with it hang when I try to close them.</p> <p>Take the following code, for example:</p> <pre><code>from pygame.locals import * pygame.init() # YEEAAH! tile_file = "blue_tile.bmp" SCREEN_SIZE = (640, 480) SCREEN_DEPTH ...
8
2010-01-08T11:06:06Z
10,788,960
<p>'if event.type==QUIT' generates a syntax error. Should be == pygame.QUIT Also, the rest of the line is incorrect but I can't see how. There's a cleaner variant <a href="http://www.petercollingridge.co.uk/pygame-physics-simulation/creating-pygame-window" rel="nofollow">here</a>:</p> <pre><code> running = True ...
2
2012-05-28T18:26:56Z
[ "python", "pygame" ]
evolution plugin for crm integration via webservices
2,027,300
<p>I have built a webservice into my companies self developed CRM system that we are in the process of integrating Outlook to the CRM for calendar sync and recording of emails related to clients.</p> <p>I want to build a plugin for the gnome evolution mail client as I use it for my work mail/calendar as I primarily ru...
0
2010-01-08T11:45:39Z
2,054,770
<p>I would start with the <a href="http://projects.gnome.org/evolution/arch.shtml" rel="nofollow">architecture</a> of Evolution. Then I would look into <a href="http://projects.gnome.org/evolution/eplugins.shtml" rel="nofollow">EPlugins</a> and start off with <a href="http://projects.gnome.org/evolution/developer-doc/e...
1
2010-01-13T06:01:06Z
[ "python", "c", "linux", "email" ]
How to put values of a list into a string
2,027,391
<p>I am trying to place several values from a list into a string. The code I have is below:</p> <pre><code>ID = [0, 1, 2] print 'ID {0}, {1}, and {2}.'.format(ID) </code></pre> <p>or </p> <pre><code>print (r'(ID\s*=\s*)(\S+)').format(ID) </code></pre> <p>This does not work. Does anyone know where I'm going wrong. ...
0
2010-01-08T12:03:35Z
2,027,409
<pre><code>&gt;&gt;&gt; 'ID {0}, {1}, and {2}.'.format(*ID) 'ID 0, 1, and 2.' </code></pre> <p>You need to unpack your list.</p> <p>Your second code doesn't make much sense.</p>
4
2010-01-08T12:07:33Z
[ "python", "string-formatting" ]
How to put values of a list into a string
2,027,391
<p>I am trying to place several values from a list into a string. The code I have is below:</p> <pre><code>ID = [0, 1, 2] print 'ID {0}, {1}, and {2}.'.format(ID) </code></pre> <p>or </p> <pre><code>print (r'(ID\s*=\s*)(\S+)').format(ID) </code></pre> <p>This does not work. Does anyone know where I'm going wrong. ...
0
2010-01-08T12:03:35Z
2,027,412
<p>You have to unpack the list.</p> <pre><code>ID = [0, 1, 2] print 'ID {0}, {1}, and {2}.'.format(*ID) </code></pre> <p>See the docs: <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow">Unpacking argument lists</a>.</p>
9
2010-01-08T12:08:05Z
[ "python", "string-formatting" ]
how to invoke sshfs within python script?
2,027,393
<p>I want to mount a remote directory using sshfs. sshfs working fine from terminal. But how to invoke it from within python script?</p> <p>I tried something like this - but didn't work at all.</p> <pre><code>import os cmd = "/usr/bin/sshfs giis@giis.co.in:/home/giis /mnt" os.system(cmd) </code></pre>
2
2010-01-08T12:03:39Z
2,027,432
<p>first, you should make sure your sshfs command works fine using the shell. Then, go to <a href="http://stackoverflow.com/search?q=subprocess+Python">here</a> to see many examples of using subprocess module of Python to call your sshfs commmand</p>
3
2010-01-08T12:10:38Z
[ "python", "sshfs" ]
Storing list variables as a string and storing it as a variable
2,027,543
<p>I am trying to enter list items into a string. I then want to store the string as a variable and print it out in another function. The code I have got so far is:</p> <pre><code>def b(): ID = [0, 1, 2] ID2 = 'ID={0}.{1}.{2}'.format(*ID) return ID2 if __name__ == '__main__': ID2 = b() def c(ID2): ...
0
2010-01-08T12:33:56Z
2,027,572
<p>How about this:</p> <pre><code>&gt;&gt;&gt; ''.join([str(x) for x in [1, 2, 3]]) '123' </code></pre>
3
2010-01-08T12:40:12Z
[ "python" ]
Storing list variables as a string and storing it as a variable
2,027,543
<p>I am trying to enter list items into a string. I then want to store the string as a variable and print it out in another function. The code I have got so far is:</p> <pre><code>def b(): ID = [0, 1, 2] ID2 = 'ID={0}.{1}.{2}'.format(*ID) return ID2 if __name__ == '__main__': ID2 = b() def c(ID2): ...
0
2010-01-08T12:33:56Z
2,027,583
<pre><code>def b(): ID = [0, 1, 2] ID2 = ('ID=%d.%d.%d' % tuple(ID)) return ID2 if __name__ == '__main__': ID2 = b() def c(ID2): print ID2 if __name__ == '__main__': myObject = c(ID2) </code></pre> <p>works for me, don't have python3 handy so cannot try with the .format()-syntax.</p> <p>However <co...
1
2010-01-08T12:43:04Z
[ "python" ]
Storing list variables as a string and storing it as a variable
2,027,543
<p>I am trying to enter list items into a string. I then want to store the string as a variable and print it out in another function. The code I have got so far is:</p> <pre><code>def b(): ID = [0, 1, 2] ID2 = 'ID={0}.{1}.{2}'.format(*ID) return ID2 if __name__ == '__main__': ID2 = b() def c(ID2): ...
0
2010-01-08T12:33:56Z
2,027,630
<p>If you want to change [0,1,2] to "0.1.2" (like version string in your previous questions), you could do like this.</p> <pre><code>&gt;&gt;&gt; '.'.join(map(str,[0, 1, 2])) '0.1.2' </code></pre>
2
2010-01-08T12:53:46Z
[ "python" ]
Storing list variables as a string and storing it as a variable
2,027,543
<p>I am trying to enter list items into a string. I then want to store the string as a variable and print it out in another function. The code I have got so far is:</p> <pre><code>def b(): ID = [0, 1, 2] ID2 = 'ID={0}.{1}.{2}'.format(*ID) return ID2 if __name__ == '__main__': ID2 = b() def c(ID2): ...
0
2010-01-08T12:33:56Z
2,027,669
<ol> <li><p>You should probably not have global variable names that match your function parameter names. It's legal but very, very confusing. And a debugging nightmare.</p></li> <li><p>You should probably not use ALL UPPERCASE VARIABLE NAMES. It's odd-looking and makes your code hard to read for experienced Python ...
2
2010-01-08T13:01:28Z
[ "python" ]
draw a border around subplots in matplotlib
2,027,592
<p>Anyone know how to draw a border around an individual subplot within a figure in matplotlib? I'm using pyplot.</p> <p>eg:</p> <pre><code>import matplotlib.pyplot as plt f = plt.figure() ax1 = f.add_subplot(211) ax2 = f.add_subplot(212) # ax1.set_edgecolor('black') </code></pre> <p>..but Axes objects have no 'edg...
7
2010-01-08T12:45:36Z
2,028,743
<p>You essentially want to draw outside of the axes, right?</p> <p>I adapted this from <a href="http://matplotlib.sourceforge.net/examples/pylab_examples/subplot_demo.html" rel="nofollow">here</a>. It would need clean up as I used some hard-coded "fudge-factors" in there.</p> <pre><code>#!/usr/bin/env python from py...
6
2010-01-08T15:52:58Z
[ "python", "matplotlib" ]
Why does not postgresql start returning rows immediately?
2,027,645
<p>The following query returns data right away:</p> <pre><code>SELECT time, value from data order by time limit 100; </code></pre> <p>Without the limit clause, it takes a long time before the server starts returning rows:</p> <pre><code>SELECT time, value from data order by time; </code></pre> <p>I observe this bot...
5
2010-01-08T12:56:51Z
2,027,660
<p>In theory, because your ORDER BY is by primary key, a sort of the results should not be necessary, and the DB could indeed return data right away in key order.</p> <p>I would expect a capable DB of noticing this, and optimizing for it. It seems that PGSQL is not. * shrug *</p> <p>You don't notice any impact if you...
0
2010-01-08T12:59:36Z
[ "python", "sql", "postgresql", "sqlalchemy" ]
Why does not postgresql start returning rows immediately?
2,027,645
<p>The following query returns data right away:</p> <pre><code>SELECT time, value from data order by time limit 100; </code></pre> <p>Without the limit clause, it takes a long time before the server starts returning rows:</p> <pre><code>SELECT time, value from data order by time; </code></pre> <p>I observe this bot...
5
2010-01-08T12:56:51Z
2,028,302
<p>The psycopg2 dbapi driver buffers the whole query result before returning any rows. You'll need to use server side cursor to incrementally fetch results. For SQLAlchemy see <a href="http://www.sqlalchemy.org/docs/05/reference/dialects/postgres.html#connecting" rel="nofollow">server_side_cursors in the docs</a> and i...
4
2010-01-08T14:52:25Z
[ "python", "sql", "postgresql", "sqlalchemy" ]
is something wrong with Python Shell (Google App)?
2,027,658
<p><a href="http://shell.appspot.com" rel="nofollow">Python Shell - shell.appspot.com</a> is acting weird? or am I missing something?</p> <pre><code>Google App Engine/1.3.0 Python 2.5.2 (r252:60911, Apr 7 2009, 17:42:26) [GCC 4.1.0] &gt;&gt;&gt; mycolors = ['red','green','blue'] &gt;&gt;&gt; mycolors.append('black'...
5
2010-01-08T12:58:55Z
2,027,679
<p>I get similar problems so I would say there is something odd going on.</p> <pre><code>&gt;&gt;&gt; a = 2 &gt;&gt;&gt; a += 3 &gt;&gt;&gt; a 5 &gt;&gt;&gt; b = [2] &gt;&gt;&gt; b += [3] &gt;&gt;&gt; b [2] &gt;&gt;&gt; [2] + [3] [2, 3] &gt;&gt;&gt; class Dave: pass &gt;&gt;&gt; d = Dave() &gt;&gt;&gt; d &lt;__main__....
1
2010-01-08T13:03:08Z
[ "python", "google-app-engine", "shell" ]
is something wrong with Python Shell (Google App)?
2,027,658
<p><a href="http://shell.appspot.com" rel="nofollow">Python Shell - shell.appspot.com</a> is acting weird? or am I missing something?</p> <pre><code>Google App Engine/1.3.0 Python 2.5.2 (r252:60911, Apr 7 2009, 17:42:26) [GCC 4.1.0] &gt;&gt;&gt; mycolors = ['red','green','blue'] &gt;&gt;&gt; mycolors.append('black'...
5
2010-01-08T12:58:55Z
2,032,504
<h3>Short Answer</h3> <p>That is a known bug. Short answer:</p> <ul> <li>Include everything on one line: <code>mycolors.append('black'); print mycolors</code></li> <li>Use my free software tool, <a href="http://con.appspot.com/" rel="nofollow">App Engine Console</a>. My code is derived from the shell and I have fixed...
4
2010-01-09T05:58:39Z
[ "python", "google-app-engine", "shell" ]
Using Python simplejson to return pregenerated json
2,027,668
<p>I have a GeoDjango model object that I want't to serialize to json. I do this in my view:</p> <pre><code>lat = float(request.GET.get('lat')) lng = float(request.GET.get('lng')) a = Authority.objects.get(area__contains=Point(lng, lat)) if a: return HttpResponse(simplejson.dumps({'name': a.name, ...
5
2010-01-08T13:01:05Z
2,027,846
<p>EDITED after author's edit:</p> <p>Can you do something like this:</p> <pre><code>lat = float(request.GET.get('lat')) lng = float(request.GET.get('lng')) a = Authority.objects.get(area__contains=Point(lng, lat)) if a: json = simplejson.dumps({'name': a.name, 'area': "{replaceme}",...
2
2010-01-08T13:33:56Z
[ "python", "django", "json", "geodjango", "simplejson" ]
Using Python simplejson to return pregenerated json
2,027,668
<p>I have a GeoDjango model object that I want't to serialize to json. I do this in my view:</p> <pre><code>lat = float(request.GET.get('lat')) lng = float(request.GET.get('lng')) a = Authority.objects.get(area__contains=Point(lng, lat)) if a: return HttpResponse(simplejson.dumps({'name': a.name, ...
5
2010-01-08T13:01:05Z
2,028,137
<p>I think the clean way to do this is by extending JSONEncoder, and creating an encoder that detects if the given object is already JSON. if it is - it just returns it. If its not, it uses the ordinary JSONEncoder to encode it.</p> <pre><code>class SkipJSONEncoder(simplejson.JSONEncoder): def default(self, obj):...
5
2010-01-08T14:23:39Z
[ "python", "django", "json", "geodjango", "simplejson" ]
Creating an image editing application in Python
2,028,025
<p>I need a tile/sprite editor kind of like Pixen, but I couldn't find one for Windows so I thought it might be a good exercise for me to try and put one together. I use Python, so are there any libraries out there that are suited to the task of putting together a simple tile/sprite editor?</p>
4
2010-01-08T14:01:15Z
2,028,035
<p>Have you looked at the <a href="http://www.pythonware.com/products/pil/" rel="nofollow">Python Imaging Library</a> (PIL)? </p>
3
2010-01-08T14:02:28Z
[ "python", "image-editor" ]
Creating an image editing application in Python
2,028,025
<p>I need a tile/sprite editor kind of like Pixen, but I couldn't find one for Windows so I thought it might be a good exercise for me to try and put one together. I use Python, so are there any libraries out there that are suited to the task of putting together a simple tile/sprite editor?</p>
4
2010-01-08T14:01:15Z
2,028,056
<p>You just need a gui toolkit (gtk, qt, wx) a image library (PIL) and 500 hours of free time ...</p>
4
2010-01-08T14:07:08Z
[ "python", "image-editor" ]
Creating an image editing application in Python
2,028,025
<p>I need a tile/sprite editor kind of like Pixen, but I couldn't find one for Windows so I thought it might be a good exercise for me to try and put one together. I use Python, so are there any libraries out there that are suited to the task of putting together a simple tile/sprite editor?</p>
4
2010-01-08T14:01:15Z
2,028,126
<p>You could try <a href="http://www.pygame.org/wiki/about" rel="nofollow">PyGame</a> but, seriously, you couldn't find a <a href="http://graphicssoft.about.com/od/pixelbasedwin/tp/freephotoedw.htm" rel="nofollow">freeware graphics editor</a> for Windows??!!</p> <p>EDIT: In the past I've used <a href="http://www.aha-s...
1
2010-01-08T14:21:40Z
[ "python", "image-editor" ]
Creating an image editing application in Python
2,028,025
<p>I need a tile/sprite editor kind of like Pixen, but I couldn't find one for Windows so I thought it might be a good exercise for me to try and put one together. I use Python, so are there any libraries out there that are suited to the task of putting together a simple tile/sprite editor?</p>
4
2010-01-08T14:01:15Z
2,029,356
<p>So, the fact is that creating a complex app with a nice UI takes <em>time</em> - I am just expanding a little bit on the answer by THC4k. </p> <p>PIL, at least PIL alone is useless for this: it does have some functions to manipulate images, but the complicate task here is creating and tunning your desired UI. </p>...
1
2010-01-08T17:26:36Z
[ "python", "image-editor" ]
How do I search through regex matches in Python?
2,028,164
<p>I need to try a string against multiple (exclusive - meaning a string that matches one of them can't match any of the other) regexes, and execute a different piece of code depending on which one it matches. What I have currently is:</p> <pre><code>m = firstre.match(str) if m: # Do something m = secondre.match(...
5
2010-01-08T14:28:21Z
2,028,253
<p>A few ideas, none of them good necessarily, but it might fit your code well:</p> <p>How about putting the code in a separate function, i.e. <code>MatchRegex()</code>, which returns which regex it matched. That way, inside the function, you can use a return after you matched the first (or second) regex, meaning you ...
1
2010-01-08T14:40:34Z
[ "python", "regex", "switch-statement" ]
How do I search through regex matches in Python?
2,028,164
<p>I need to try a string against multiple (exclusive - meaning a string that matches one of them can't match any of the other) regexes, and execute a different piece of code depending on which one it matches. What I have currently is:</p> <pre><code>m = firstre.match(str) if m: # Do something m = secondre.match(...
5
2010-01-08T14:28:21Z
2,028,260
<pre><code>def doit( s ): # with some side-effect on a a = [] def f1( s, m ): a.append( 1 ) print 'f1', a, s, m def f2( s, m ): a.append( 2 ) print 'f2', a, s, m def f3( s, m ): a.append( 3 ) print 'f3', a, s, m re1 = re.compile( 'one' ) ...
4
2010-01-08T14:42:46Z
[ "python", "regex", "switch-statement" ]
How do I search through regex matches in Python?
2,028,164
<p>I need to try a string against multiple (exclusive - meaning a string that matches one of them can't match any of the other) regexes, and execute a different piece of code depending on which one it matches. What I have currently is:</p> <pre><code>m = firstre.match(str) if m: # Do something m = secondre.match(...
5
2010-01-08T14:28:21Z
2,028,271
<p>This might be a bit over engineering the solution, but you could combine them as a single regexp with named groups and see which group matched. This could be encapsulated as a helper class:</p> <pre><code>import re class MultiRe(object): def __init__(self, **regexps): self.keys = regexps.keys() ...
3
2010-01-08T14:45:16Z
[ "python", "regex", "switch-statement" ]
How do I search through regex matches in Python?
2,028,164
<p>I need to try a string against multiple (exclusive - meaning a string that matches one of them can't match any of the other) regexes, and execute a different piece of code depending on which one it matches. What I have currently is:</p> <pre><code>m = firstre.match(str) if m: # Do something m = secondre.match(...
5
2010-01-08T14:28:21Z
2,028,479
<p>Early returns, perhaps?</p> <pre><code>def doit(s): m = re1.match(s) if m: # Do something return m = re2.match(s) if m: # Do something else return ... </code></pre> <p>Ants Aasma's answer is good too. If you prefer less scaffolding you can write that out yourse...
0
2010-01-08T15:16:01Z
[ "python", "regex", "switch-statement" ]
How do I search through regex matches in Python?
2,028,164
<p>I need to try a string against multiple (exclusive - meaning a string that matches one of them can't match any of the other) regexes, and execute a different piece of code depending on which one it matches. What I have currently is:</p> <pre><code>m = firstre.match(str) if m: # Do something m = secondre.match(...
5
2010-01-08T14:28:21Z
2,029,060
<p>Do it with an elif in case you just need a True/False out of regex matching:</p> <pre><code>if regex1.match(str): # do stuff elif regex2.match(str): # and so on </code></pre>
0
2010-01-08T16:37:02Z
[ "python", "regex", "switch-statement" ]
How do I search through regex matches in Python?
2,028,164
<p>I need to try a string against multiple (exclusive - meaning a string that matches one of them can't match any of the other) regexes, and execute a different piece of code depending on which one it matches. What I have currently is:</p> <pre><code>m = firstre.match(str) if m: # Do something m = secondre.match(...
5
2010-01-08T14:28:21Z
2,029,527
<p>You could use</p> <pre><code>def do_first(str, res, actions): for re,action in zip(res, actions): m = re.match(str) if m: action(str) return </code></pre> <p>So, for example, say you've defined</p> <pre><code>def do_something_1(str): print "#1: %s" % str def do_something_2(str): print "...
1
2010-01-08T17:50:18Z
[ "python", "regex", "switch-statement" ]
How do I search through regex matches in Python?
2,028,164
<p>I need to try a string against multiple (exclusive - meaning a string that matches one of them can't match any of the other) regexes, and execute a different piece of code depending on which one it matches. What I have currently is:</p> <pre><code>m = firstre.match(str) if m: # Do something m = secondre.match(...
5
2010-01-08T14:28:21Z
2,029,636
<p>This is a good application for the undocumented but quite useful <a href="http://code.activestate.com/recipes/457664/" rel="nofollow">re.Scanner</a> class.</p>
3
2010-01-08T18:08:02Z
[ "python", "regex", "switch-statement" ]
wrapping cmd.exe with subprocess
2,028,207
<p>Hi I try to wrap cmd.exe under windows with the following program but it doesn't work , it seems to wait for something and doesn't display anything. Any idea what is wrong here ?</p> <pre><code>import subprocess process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stde...
2
2010-01-08T14:34:26Z
2,028,246
<p>Usually when trying to call command prompt with an actual command, it is simpler to just call it with the "/k" parameter rather than passing commands in via stdin. That is, just call "cmd.exe /k dir". For example, </p> <pre><code>from os import * a = popen("cmd /k dir") print (a.read()) </code></pre> <p>The code...
4
2010-01-08T14:39:36Z
[ "python", "windows", "subprocess" ]
wrapping cmd.exe with subprocess
2,028,207
<p>Hi I try to wrap cmd.exe under windows with the following program but it doesn't work , it seems to wait for something and doesn't display anything. Any idea what is wrong here ?</p> <pre><code>import subprocess process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stde...
2
2010-01-08T14:34:26Z
2,028,337
<pre><code>process = subprocess.Popen('cmd.exe /k ', shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None) process.stdin.write("dir\n") o,e=process.communicate() print o process.stdin.close() </code></pre> <p>by the way, if your actual task is really to do a directory listing, please use Python's own o...
3
2010-01-08T14:57:21Z
[ "python", "windows", "subprocess" ]
wrapping cmd.exe with subprocess
2,028,207
<p>Hi I try to wrap cmd.exe under windows with the following program but it doesn't work , it seems to wait for something and doesn't display anything. Any idea what is wrong here ?</p> <pre><code>import subprocess process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stde...
2
2010-01-08T14:34:26Z
2,029,207
<p>This locks up because <code>process.stdout.readlines()</code> reads all output by the process (until it terminates). Since cmd.exe is still running, it keeps waiting forever for it to close.</p> <p>To fix this, you can start a separate thread to read the process output. This is something you need to do anyway if yo...
2
2010-01-08T16:58:19Z
[ "python", "windows", "subprocess" ]
invoking pylint programmatically
2,028,268
<p>I'd like to invoke the pylint checker, limited to the Error signalling part, as part of my unit testing. so I checked the pylint executable script, got to the <code>pylint.lint.Run</code> helper class and there I got lost in a quite long <code>__init__</code> function, ending with a call to <code>sys.exit()</code>....
18
2010-01-08T14:44:58Z
2,062,665
<p>Take a look at the <code>pylint/epylint.py</code> which contains <em>two</em> different ways to start pylint programatically. </p> <p>You can also simply call :</p> <pre><code>from pylint.lint import Run Run(['--errors-only', 'myfile.py']) </code></pre> <p>for instance.</p>
15
2010-01-14T07:03:31Z
[ "python", "coding-style", "automated-tests", "pylint" ]
invoking pylint programmatically
2,028,268
<p>I'd like to invoke the pylint checker, limited to the Error signalling part, as part of my unit testing. so I checked the pylint executable script, got to the <code>pylint.lint.Run</code> helper class and there I got lost in a quite long <code>__init__</code> function, ending with a call to <code>sys.exit()</code>....
18
2010-01-08T14:44:58Z
4,803,466
<p>I'm glad I came across this. I used some of the answers here and some initiative to come up with:</p> <pre><code># a simple class with a write method class WritableObject: def __init__(self): self.content = [] def write(self, string): self.content.append(string) pylint_output = WritableObjec...
3
2011-01-26T10:27:01Z
[ "python", "coding-style", "automated-tests", "pylint" ]
invoking pylint programmatically
2,028,268
<p>I'd like to invoke the pylint checker, limited to the Error signalling part, as part of my unit testing. so I checked the pylint executable script, got to the <code>pylint.lint.Run</code> helper class and there I got lost in a quite long <code>__init__</code> function, ending with a call to <code>sys.exit()</code>....
18
2010-01-08T14:44:58Z
7,919,648
<p>I got the same problem recently. syt is right, <code>pylint.epylint</code> got several methods in there. However they all call a subprocess in which python is launched again. In my case, this was getting quite slow.</p> <p>Building from mcarans answer, and finding that there is a flag exit, I did the following</p>...
8
2011-10-27T17:06:39Z
[ "python", "coding-style", "automated-tests", "pylint" ]
invoking pylint programmatically
2,028,268
<p>I'd like to invoke the pylint checker, limited to the Error signalling part, as part of my unit testing. so I checked the pylint executable script, got to the <code>pylint.lint.Run</code> helper class and there I got lost in a quite long <code>__init__</code> function, ending with a call to <code>sys.exit()</code>....
18
2010-01-08T14:44:58Z
36,333,817
<p>Instead of creating a WritableObject class we can use StringIO. StringIO contains write method.</p> <pre><code>import sys try: from io import StringIO except: from StringIO import StringIO stdout = sys.stdout sys.stdout = StringIO() ARGS = ["-r","n", "--rcfile=rcpylint"] r = lint.Run(['../test.py']+ARGS, ...
0
2016-03-31T12:41:38Z
[ "python", "coding-style", "automated-tests", "pylint" ]