title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
How do I coherently organize modules for a PyGTK desktop application? | 216,093 | <p>I am working on a desktop application in PyGTK and seem to be bumping up against some limitations of my file organization. Thus far I've structured my project this way:</p>
<ul>
<li>application.py - holds the primary application class (most functional routines)</li>
<li>gui.py - holds a loosely coupled GTK gui implementation. Handles signal callbacks, etc.</li>
<li>command.py - holds command line automation functions not dependent on data in the application class</li>
<li>state.py - holds the state data persistence class</li>
</ul>
<p>This has served fairly well so far, but at this point application.py is starting to get rather long. I have looked at numerous other PyGTK applications and they seem to have similar structural issues. At a certain point the primary module starts to get very long and there is not obvious way of breaking the code out into narrower modules without sacrificing clarity and object orientation.</p>
<p>I have considered making the GUI the primary module and having seperate modules for the toolbar routines, the menus routines, etc, but at that point I believe I will lose most of the benefits of OOP and end up with an everything-references-everything scenario.</p>
<p>Should I just deal with having a very long central module or is there a better way of structuring the project so that I don't have to rely on the class browser so much?</p>
<p><strong>EDIT I</strong></p>
<p>Ok, so point taken regarding all the MVC stuff. I do have a rough approximation of MVC in my code, but admittedly I could probably gain some mileage by further segregating the model and controller. However, I am reading over python-gtkmvc's documentation (which is a great find by the way, thank you for referencing it) and my impression is that its not going to solve my problem so much as just formalize it. My application is a single glade file, generally a single window. So no matter how tightly I define the MVC roles of the modules I'm still going to have one controller module doing most everything, which is pretty much what I have now. Admittedly I'm a little fuzzy on proper MVC implementation and I'm going to keep researching, but it doesn't look to me like this architecture is going to get any more stuff out of my main file, its just going to rename that file to controller.py.</p>
<p>Should I be thinking about separate Controller/View pairs for seperate sections of the window (the toolbar, the menus, etc)? Perhaps that is what I'm missing here. It seems that this is what S. Lott is referring to in his second bullet point.</p>
<p>Thanks for the responses so far.</p>
| 7 | 2008-10-19T06:07:28Z | 219,737 | <p>So having not heard back regarding my edit to the original question, I have done some more research and the conclusion I seem to be coming to is that <em>yes</em>, I should break the interface out into several views, each with its own controller. Python-gtkmvc provides the ability to this by providing a <code>glade_top_widget_name</code> parameter to the View constructor. This all seems to make a good deal of sense although it is going to require a large refactoring of my existing codebase which I may or may not be willing to undertake in the near-term (I know, I know, I <em>should</em>.) Moreover, I'm left to wonder whether should just have a single Model object (my application is fairly simple--no more than twenty-five state vars) or if I should break it out into multiple models and have to deal with controllers observing multiple models and chaining notifications across them. (Again, I know I really <em>should</em> do the latter.) If anyone has any further insight, I still don't really feel like I've gotten an answer to the original question, although I have a direction to head in now.</p>
<p>(Moreover it seems like their ought to be other architectural choices at hand, given that up until now I had not seen a single Python application coded in the MVC style, but then again many Python applications tend to have the exact problem I've described above.)</p>
| 0 | 2008-10-20T20:15:32Z | [
"python",
"gtk",
"module",
"pygtk",
"organization"
] |
How do I coherently organize modules for a PyGTK desktop application? | 216,093 | <p>I am working on a desktop application in PyGTK and seem to be bumping up against some limitations of my file organization. Thus far I've structured my project this way:</p>
<ul>
<li>application.py - holds the primary application class (most functional routines)</li>
<li>gui.py - holds a loosely coupled GTK gui implementation. Handles signal callbacks, etc.</li>
<li>command.py - holds command line automation functions not dependent on data in the application class</li>
<li>state.py - holds the state data persistence class</li>
</ul>
<p>This has served fairly well so far, but at this point application.py is starting to get rather long. I have looked at numerous other PyGTK applications and they seem to have similar structural issues. At a certain point the primary module starts to get very long and there is not obvious way of breaking the code out into narrower modules without sacrificing clarity and object orientation.</p>
<p>I have considered making the GUI the primary module and having seperate modules for the toolbar routines, the menus routines, etc, but at that point I believe I will lose most of the benefits of OOP and end up with an everything-references-everything scenario.</p>
<p>Should I just deal with having a very long central module or is there a better way of structuring the project so that I don't have to rely on the class browser so much?</p>
<p><strong>EDIT I</strong></p>
<p>Ok, so point taken regarding all the MVC stuff. I do have a rough approximation of MVC in my code, but admittedly I could probably gain some mileage by further segregating the model and controller. However, I am reading over python-gtkmvc's documentation (which is a great find by the way, thank you for referencing it) and my impression is that its not going to solve my problem so much as just formalize it. My application is a single glade file, generally a single window. So no matter how tightly I define the MVC roles of the modules I'm still going to have one controller module doing most everything, which is pretty much what I have now. Admittedly I'm a little fuzzy on proper MVC implementation and I'm going to keep researching, but it doesn't look to me like this architecture is going to get any more stuff out of my main file, its just going to rename that file to controller.py.</p>
<p>Should I be thinking about separate Controller/View pairs for seperate sections of the window (the toolbar, the menus, etc)? Perhaps that is what I'm missing here. It seems that this is what S. Lott is referring to in his second bullet point.</p>
<p>Thanks for the responses so far.</p>
| 7 | 2008-10-19T06:07:28Z | 252,361 | <p>Sorry to answer so late. <a href="http://async.com.br/projects/kiwi" rel="nofollow">Kiwi</a> seems to me a far better solution than gtkmvc. It is my first dependency for any pygtk project.</p>
| 2 | 2008-10-31T01:31:40Z | [
"python",
"gtk",
"module",
"pygtk",
"organization"
] |
How do I reverse a list using recursion in Python? | 216,119 | <p>I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?</p>
| 0 | 2008-10-19T06:56:01Z | 216,123 | <p>Take the first element, reverse the rest of the list recursively, and append the first element at the end of the list.</p>
| 1 | 2008-10-19T07:02:44Z | [
"python",
"list",
"recursion"
] |
How do I reverse a list using recursion in Python? | 216,119 | <p>I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?</p>
| 0 | 2008-10-19T06:56:01Z | 216,132 | <p>The trick is to join <em>after</em> recursing:</p>
<pre>
def backwards(l):
if not l:
return
x, y = l[0], l[1:]
return backwards(y) + [x]
</pre>
| 2 | 2008-10-19T07:14:33Z | [
"python",
"list",
"recursion"
] |
How do I reverse a list using recursion in Python? | 216,119 | <p>I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?</p>
| 0 | 2008-10-19T06:56:01Z | 216,136 | <p>Append the first element of the list to a reversed sublist:</p>
<pre><code>mylist = [1, 2, 3, 4, 5]
backwards = lambda l: (backwards (l[1:]) + l[:1] if l else [])
print backwards (mylist)
</code></pre>
| 9 | 2008-10-19T07:20:02Z | [
"python",
"list",
"recursion"
] |
How do I reverse a list using recursion in Python? | 216,119 | <p>I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?</p>
| 0 | 2008-10-19T06:56:01Z | 216,168 | <p>A bit more explicit:</p>
<pre><code>def rev(l):
if len(l) == 0: return []
return [l[-1]] + rev(l[:-1])
</code></pre>
<p><hr></p>
<p>This turns into:</p>
<pre><code>def rev(l):
if not l: return []
return [l[-1]] + rev(l[:-1])
</code></pre>
<p>Which turns into:</p>
<pre><code>def rev(l):
return [l[-1]] + rev(l[:-1]) if l else []
</code></pre>
<p>Which is the same as another answer.</p>
<p><hr></p>
<p>Tail recursive / CPS style (which python doesn't optimize for anyway):</p>
<pre><code>def rev(l, k):
if len(l) == 0: return k([])
def b(res):
return k([l[-1]] + res)
return rev(l[:-1],b)
>>> rev([1, 2, 3, 4, 5], lambda x: x)
[5, 4, 3, 2, 1]
</code></pre>
| 5 | 2008-10-19T08:18:43Z | [
"python",
"list",
"recursion"
] |
How do I reverse a list using recursion in Python? | 216,119 | <p>I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?</p>
| 0 | 2008-10-19T06:56:01Z | 216,184 | <p>I know it's not a helpful answer (though this question has been already answered), but in any real code, please don't do that. Python cannot optimize tail-calls, has slow function calls and has a fixed recursion depth, so there are at least 3 reasons why to do it iteratively instead.</p>
| 6 | 2008-10-19T08:50:19Z | [
"python",
"list",
"recursion"
] |
How do I reverse a list using recursion in Python? | 216,119 | <p>I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?</p>
| 0 | 2008-10-19T06:56:01Z | 217,204 | <p>This one reverses in place. (Of course an iterative version would be better, but it has to be recursive, hasn't it?)</p>
<pre><code>def reverse(l, first=0, last=-1):
if first >= len(l)/2: return
l[first], l[last] = l[last], l[first]
reverse(l, first+1, last-1)
mylist = [1,2,3,4,5]
print mylist
reverse(mylist)
print mylist
</code></pre>
| 1 | 2008-10-20T00:11:43Z | [
"python",
"list",
"recursion"
] |
How do I reverse a list using recursion in Python? | 216,119 | <p>I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?</p>
| 0 | 2008-10-19T06:56:01Z | 2,105,565 | <pre><code>def reverse(q):
if len(q) != 0:
temp = q.pop(0)
reverse(q)
q.append(temp)
return q
</code></pre>
| 1 | 2010-01-20T22:36:52Z | [
"python",
"list",
"recursion"
] |
How do I reverse a list using recursion in Python? | 216,119 | <p>I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?</p>
| 0 | 2008-10-19T06:56:01Z | 35,097,940 | <pre><code>def revList(alist):
if len(alist) == 1:
return alist #base case
else:
return revList(alist[1:]) + [alist[0]]
print revList([1,2,3,4])
#prints [4,3,2,1]
</code></pre>
| 0 | 2016-01-30T04:21:54Z | [
"python",
"list",
"recursion"
] |
How do I reverse a list using recursion in Python? | 216,119 | <p>I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?</p>
| 0 | 2008-10-19T06:56:01Z | 35,679,380 | <pre><code>def reverseList(listName,newList = None):
if newList == None:
newList = []
if len(listName)>0:
newList.append((listName.pop()))
return reverseList(listName, newList)
else:
return newList
</code></pre>
<p>print reverseList([1,2,3,4])
[4,3,2,1]</p>
| 0 | 2016-02-28T06:09:27Z | [
"python",
"list",
"recursion"
] |
How do I reverse a list using recursion in Python? | 216,119 | <p>I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?</p>
| 0 | 2008-10-19T06:56:01Z | 39,977,940 | <p>Using Mutable default argument and recursion :</p>
<pre><code>def hello(x,d=[]):
d.append(x[-1])
if len(x)<=1:
s="".join(d)
print(s)
else:
return hello(x[:-1])
hello("word")
</code></pre>
<h1>additional info</h1>
<pre><code>x[-1] # last item in the array
x[-2:] # last two items in the array
x[:-2] # everything except the last two items
</code></pre>
<p>Recursion part is <code>hello(x[:-1])</code> where its calling hello function again after <code>x[:-1]</code> </p>
| 1 | 2016-10-11T13:05:51Z | [
"python",
"list",
"recursion"
] |
How do I reverse a list using recursion in Python? | 216,119 | <p>I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?</p>
| 0 | 2008-10-19T06:56:01Z | 39,978,152 | <p>Why not:</p>
<pre><code>a = [1,2,3,4,5]
a = [a[i] for i in xrange(len(a)-1, -1, -1)] # now a is reversed!
</code></pre>
| 1 | 2016-10-11T13:16:19Z | [
"python",
"list",
"recursion"
] |
Smart Sudoku Golf | 216,141 | <p>The point of this question is to create the shortest <b>not abusively slow</b> Sudoku solver. This is defined as: <b>don't recurse when there are spots on the board which can only possibly be one digit</b>.</p>
<p>Here is the shortest I have so far in python:</p>
<pre><code>r=range(81)
s=range(1,10)
def R(A):
bzt={}
for i in r:
if A[i]!=0: continue;
h={}
for j in r:
h[A[j]if(j/9==i/9 or j%9==i%9 or(j/27==i/27)and((j%9/3)==(i%9/3)))else 0]=1
bzt[9-len(h)]=h,i
for l,(h,i)in sorted(bzt.items(),key=lambda x:x[0]):
for j in s:
if j not in h:
A[i]=j
if R(A):return 1
A[i]=0;return 0
print A;return 1
R(map(int, "080007095010020000309581000500000300400000006006000007000762409000050020820400060"))
</code></pre>
<p>The last line I take to be part of the cmd line input, it can be changed to:</p>
<pre><code>import sys; R(map(int, sys.argv[1]);
</code></pre>
<p>This is similar to other sudoku golf challenges, except that I want to eliminate unnecessary recursion. Any language is acceptable. The challenge is on!</p>
| 2 | 2008-10-19T07:38:32Z | 216,603 | <p>I've just trimmed the python a bit here:</p>
<pre><code>r=range(81);s=range(1,10)
def R(A):
z={}
for i in r:
if A[i]!=0:continue
h={}
for j in r:h[A[j]if j/9==i/9 or j%9==i%9 or j/27==i/27 and j%9/3==i%9/3 else 0]=1
z[9-len(h)]=h,i
for l,(h,i)in sorted(z.items(),cmp,lambda x:x[0]):
for j in s:
if j not in h:
A[i]=j
if R(A):return A
A[i]=0;return[]
return A
print R(map(int, "080007095010020000309581000500000300400000006006000007000762409000050020820400060"))
</code></pre>
<p>This is a hefty 410 characters, 250 if you don't count whitespace. If you just turn it into perl you'll undoubtedly be better than mine!</p>
| 2 | 2008-10-19T16:19:42Z | [
"python",
"perl",
"code-golf",
"sudoku"
] |
Smart Sudoku Golf | 216,141 | <p>The point of this question is to create the shortest <b>not abusively slow</b> Sudoku solver. This is defined as: <b>don't recurse when there are spots on the board which can only possibly be one digit</b>.</p>
<p>Here is the shortest I have so far in python:</p>
<pre><code>r=range(81)
s=range(1,10)
def R(A):
bzt={}
for i in r:
if A[i]!=0: continue;
h={}
for j in r:
h[A[j]if(j/9==i/9 or j%9==i%9 or(j/27==i/27)and((j%9/3)==(i%9/3)))else 0]=1
bzt[9-len(h)]=h,i
for l,(h,i)in sorted(bzt.items(),key=lambda x:x[0]):
for j in s:
if j not in h:
A[i]=j
if R(A):return 1
A[i]=0;return 0
print A;return 1
R(map(int, "080007095010020000309581000500000300400000006006000007000762409000050020820400060"))
</code></pre>
<p>The last line I take to be part of the cmd line input, it can be changed to:</p>
<pre><code>import sys; R(map(int, sys.argv[1]);
</code></pre>
<p>This is similar to other sudoku golf challenges, except that I want to eliminate unnecessary recursion. Any language is acceptable. The challenge is on!</p>
| 2 | 2008-10-19T07:38:32Z | 217,114 | <p>I haven't really made much of a change - the algorithm is identical, but here are a few further micro-optimisations you can make to your python code.</p>
<ul>
<li><p>No need for !=0, 0 is false in a boolean context.</p></li>
<li><p>a if c else b is more expensive than using [a,b][c] if you don't need short-circuiting, hence you can use <code>h[ [0,A[j]][j/9.. rest of boolean condition]</code>. Even better is to exploit the fact that you want 0 in the false case, and so multiply by the boolean value (treated as either <code>0*A[j]</code> (ie. 0) or <code>1*A[j]</code> (ie. <code>A[j]</code>).</p></li>
<li><p>You can omit spaces between digits and identifiers. eg "<code>9 or</code>" -> "<code>9or</code>"</p></li>
<li><p>You can omit the key to sorted(). Since you're sorting on the first element, a normal sort will produce effectively the same order (unless you're relying on stability, which it doesn't look like)</p></li>
<li><p>You can save a couple of bytes by omitting the .items() call, and just assign h,i in the next line to z[l]</p></li>
<li><p>You only use s once - no point in using a variable. You can also avoid using range() by selecting the appropriate slice of r instead (r[1:10])</p></li>
<li><p><code>j not in h</code> can become <code>(j in h)-1</code> (relying on True == 1 in integer context)</p></li>
<li><p><strong>[Edit]</strong> You can also replace the first for loop's construction of h with a dict constructor and a generator expression. This lets you compress the logic onto one line, saving 10 bytes in total.</p></li>
</ul>
<p>More generally, you probably want to think about ways to change the algorithm to reduce the levels of nesting. Every level gives an additional byte per line within in python, which accumulates.</p>
<p>Here's what I've got so far (I've switched to 1 space per indent so that you can get an accurate picture of required characters. Currently it's weighing in at <strike>288</strike> 278, which is still pretty big.</p>
<pre><code>r=range(81)
def R(A):
z={}
for i in r:
if 0==A[i]:h=dict((A[j]*(j/9==i/9or j%9==i%9or j/27==i/27and j%9/3==i%9/3),1)for j in r);z[9-len(h)]=h,i
for l in sorted(z):
h,i=z[l]
for j in r[1:10]:
if(j in h)-1:
A[i]=j
if R(A):return A
A[i]=0;return[]
return A
</code></pre>
| 3 | 2008-10-19T22:54:37Z | [
"python",
"perl",
"code-golf",
"sudoku"
] |
Smart Sudoku Golf | 216,141 | <p>The point of this question is to create the shortest <b>not abusively slow</b> Sudoku solver. This is defined as: <b>don't recurse when there are spots on the board which can only possibly be one digit</b>.</p>
<p>Here is the shortest I have so far in python:</p>
<pre><code>r=range(81)
s=range(1,10)
def R(A):
bzt={}
for i in r:
if A[i]!=0: continue;
h={}
for j in r:
h[A[j]if(j/9==i/9 or j%9==i%9 or(j/27==i/27)and((j%9/3)==(i%9/3)))else 0]=1
bzt[9-len(h)]=h,i
for l,(h,i)in sorted(bzt.items(),key=lambda x:x[0]):
for j in s:
if j not in h:
A[i]=j
if R(A):return 1
A[i]=0;return 0
print A;return 1
R(map(int, "080007095010020000309581000500000300400000006006000007000762409000050020820400060"))
</code></pre>
<p>The last line I take to be part of the cmd line input, it can be changed to:</p>
<pre><code>import sys; R(map(int, sys.argv[1]);
</code></pre>
<p>This is similar to other sudoku golf challenges, except that I want to eliminate unnecessary recursion. Any language is acceptable. The challenge is on!</p>
| 2 | 2008-10-19T07:38:32Z | 217,569 | <pre><code>r=range(81)
def R(A):
if(0in A)-1:yield A;return
def H(i):h=set(A[j]for j in r if j/9==i/9or j%9==i%9or j/27==i/27and j%9/3==i%9/3);return len(h),h,i
l,h,i=max(H(i)for i in r if not A[i])
for j in r[1:10]:
if(j in h)-1:
A[i]=j
for S in R(A):yield S
A[i]=0
</code></pre>
<p>269 characters, and it finds all solutions. Usage (not counted in char count):</p>
<pre><code>sixsol = map(int, "300000080001093000040780003093800012000040000520006790600021040000530900030000051")
for S in R(sixsol):
print S
</code></pre>
| 3 | 2008-10-20T05:12:33Z | [
"python",
"perl",
"code-golf",
"sudoku"
] |
How close are development webservers to production webservers? | 216,489 | <p>Most python frameworks will have a development webserver of some kind that will have a warning that it isn't for use as production servers. How much different do they tend to be from their production equivalents?</p>
<p>I haven't quite decided which framework to go with, much less what production server to use, so it's kinda difficult for me to pin this down to a "compare development server x to production server y." So with that said, let me make the question a little bit more precise: In your past experience with a python framework, how much time did you have to spend getting your application up and running with a production system once its been developed on a development server? Or did you skip the development server and develop your app on a server that's more like what you will use in production?</p>
| 5 | 2008-10-19T14:45:47Z | 216,495 | <p>Generally, they are same in terms of the settings which are required to run the applications which include the environment setting. <br>
However, the clients genereally have dev systems which are less powerful in terms of the processing power and other h/w resources. I have seen using them virtual servers in dev evironment since they generally have multiple projects going on in parallel an this helps them reducing the cost.</p>
| 2 | 2008-10-19T14:50:57Z | [
"python",
"webserver",
"web-frameworks"
] |
How close are development webservers to production webservers? | 216,489 | <p>Most python frameworks will have a development webserver of some kind that will have a warning that it isn't for use as production servers. How much different do they tend to be from their production equivalents?</p>
<p>I haven't quite decided which framework to go with, much less what production server to use, so it's kinda difficult for me to pin this down to a "compare development server x to production server y." So with that said, let me make the question a little bit more precise: In your past experience with a python framework, how much time did you have to spend getting your application up and running with a production system once its been developed on a development server? Or did you skip the development server and develop your app on a server that's more like what you will use in production?</p>
| 5 | 2008-10-19T14:45:47Z | 216,505 | <p>Ideally, the logical configuration of the development, test, and production server should be the same. They should have the same version of OS, web server, and all other software assets used to run the application. However, depending on how strong your environment things will crop - hand copied images/scripts etc on the dev machine that do not make it through test and or production.</p>
<p>to minimize this you probably need some sort of push script that can move you from one stage to the next, ie PushVersionDev, PushVesionTest,PushVersionProd. ideally this should be the same script with parameters for target server(s) representing all that you need to move the app through the various stages. </p>
<p>I would recommend a read of Theo Schlossnagle's book <a href="http://astore.amazon.com/possiboutpos-20/detail/067232699X/105-2710068-5490858" rel="nofollow">Scalable Internet Architectures</a> for more ideas on the matter.</p>
<p>To answer your question directly....once you get your application tested and implemented, the time to roll to productoin is not great - deploy OS, web server, supporting frameworks if they need installation, application and you are good to go. From bare metal I have seen linux servers go online in 1 hour, windows about 90 minutes. if you have the OS and web server going even less..minutes.</p>
| 1 | 2008-10-19T15:06:47Z | [
"python",
"webserver",
"web-frameworks"
] |
How close are development webservers to production webservers? | 216,489 | <p>Most python frameworks will have a development webserver of some kind that will have a warning that it isn't for use as production servers. How much different do they tend to be from their production equivalents?</p>
<p>I haven't quite decided which framework to go with, much less what production server to use, so it's kinda difficult for me to pin this down to a "compare development server x to production server y." So with that said, let me make the question a little bit more precise: In your past experience with a python framework, how much time did you have to spend getting your application up and running with a production system once its been developed on a development server? Or did you skip the development server and develop your app on a server that's more like what you will use in production?</p>
| 5 | 2008-10-19T14:45:47Z | 216,628 | <p>The lower environments should try to match the production environment as closely as possible given the resources available. This applies to all development efforts regardless of whether they are python-based or even web-based. In practical terms, most organizations are not willing to spend that type of money. In this case try to make at least the environment that is directly below production as close to production as possible.</p>
<p>Some of the variable to keep in mind are:</p>
<ul>
<li><p>many times there are multiple machines (app server, database server, web server, load balancers, fire walls, etc) in a production. Keep these all in mind.</p></li>
<li><p>Operating Systems</p></li>
<li><p>number of CPUs. Moving from a one CPU lower environment to a multi core production environment can expose multi-threading issues that were not tested</p></li>
<li><p>load balancing. Many times lower environments are not load balanced. If you are replicating sessions (for instance) across multiple production app servers, you should try to do the same in a lower environment</p></li>
<li><p>Software / library versions</p></li>
</ul>
| 5 | 2008-10-19T16:36:03Z | [
"python",
"webserver",
"web-frameworks"
] |
How close are development webservers to production webservers? | 216,489 | <p>Most python frameworks will have a development webserver of some kind that will have a warning that it isn't for use as production servers. How much different do they tend to be from their production equivalents?</p>
<p>I haven't quite decided which framework to go with, much less what production server to use, so it's kinda difficult for me to pin this down to a "compare development server x to production server y." So with that said, let me make the question a little bit more precise: In your past experience with a python framework, how much time did you have to spend getting your application up and running with a production system once its been developed on a development server? Or did you skip the development server and develop your app on a server that's more like what you will use in production?</p>
| 5 | 2008-10-19T14:45:47Z | 216,653 | <p>I develop with django. The production server we have is remote, so it's a pain to be using it for development. Thus, at first, I created a vm and tried to match as closely as I could the environment of the prod server. At some point that vm got hosed (due to an unrelated incident). I took stock of the situation at that time and realized there really was no good reason to be using a customized vm for development. Since the resources available to the app weren't the same as the prod server, it was no good for timing queries anyway (in an absolute sense).</p>
<p>That said, I now use django's built in dev server with sqlite for development, and apache/wsgi and postgresql for production. As long as the python dependencies are met on both sides, it's 100% compatible. The only potential problem would be writing raw sql instead of using the orm.</p>
| 2 | 2008-10-19T16:50:49Z | [
"python",
"webserver",
"web-frameworks"
] |
How close are development webservers to production webservers? | 216,489 | <p>Most python frameworks will have a development webserver of some kind that will have a warning that it isn't for use as production servers. How much different do they tend to be from their production equivalents?</p>
<p>I haven't quite decided which framework to go with, much less what production server to use, so it's kinda difficult for me to pin this down to a "compare development server x to production server y." So with that said, let me make the question a little bit more precise: In your past experience with a python framework, how much time did you have to spend getting your application up and running with a production system once its been developed on a development server? Or did you skip the development server and develop your app on a server that's more like what you will use in production?</p>
| 5 | 2008-10-19T14:45:47Z | 217,467 | <p>Your staging environment should mimic your production environment. Development is more like a playground, and the control on the development environment should not be quite so strict. However, the development environment should periodically be refreshed from the production environment (e.g,. prod data copied to the dev db, close the ports on dev that are closed on prod, etc.).</p>
<p>Ideally, dev, stage, and prod are all on separate machines. The separate machines can be separate physical boxes, or virtual machines on the same physical box, depending on budget/needs.</p>
| 0 | 2008-10-20T03:38:02Z | [
"python",
"webserver",
"web-frameworks"
] |
Group by date in a particular format in SQLAlchemy | 216,657 | <p>I have a table called logs which has a datetime field.
I want to select the date and count of rows based on a particular date format. </p>
<p>How do I do this using SQLAlchemy?</p>
| 1 | 2008-10-19T16:52:44Z | 216,730 | <p>I don't know SQLAlchemy, so I could be off-target. However, I think that all you need is:</p>
<pre><code>SELECT date_formatter(datetime_field, "format-specification") AS dt_field, COUNT(*)
FROM logs
GROUP BY date_formatter(datetime_field, "format-specification")
ORDER BY 1;
</code></pre>
<p>OK, maybe you don't need the ORDER BY, and maybe it would be better to re-specify the date expression. There are likely to be alternatives, such as:</p>
<pre><code>SELECT dt_field, COUNT(*)
FROM (SELECT date_formatter(datetime_field, "format-specification") AS dt_field
FROM logs) AS necessary
GROUP BY dt_field
ORDER BY dt_field;
</code></pre>
<p>And so on and so forth. Basically, you format the datetime field and then proceed to do the grouping etc on the formatted value.</p>
| 0 | 2008-10-19T17:50:23Z | [
"python",
"sql",
"sqlalchemy"
] |
Group by date in a particular format in SQLAlchemy | 216,657 | <p>I have a table called logs which has a datetime field.
I want to select the date and count of rows based on a particular date format. </p>
<p>How do I do this using SQLAlchemy?</p>
| 1 | 2008-10-19T16:52:44Z | 216,757 | <p>Does counting yield the same result when you just group by the unformatted datetime column? If so, you could just run the query and use Python date's strftime() method afterwards. i.e.</p>
<pre><code>query = select([logs.c.datetime, func.count(logs.c.datetime)]).group_by(logs.c.datetime)
results = session.execute(query).fetchall()
results = [(t[0].strftime("..."), t[1]) for t in results]
</code></pre>
| 1 | 2008-10-19T18:11:32Z | [
"python",
"sql",
"sqlalchemy"
] |
Group by date in a particular format in SQLAlchemy | 216,657 | <p>I have a table called logs which has a datetime field.
I want to select the date and count of rows based on a particular date format. </p>
<p>How do I do this using SQLAlchemy?</p>
| 1 | 2008-10-19T16:52:44Z | 218,974 | <p>I don't know of a generic SQLAlchemy answer. Most databases support some form of date formatting, typically via functions. SQLAlchemy supports calling functions via sqlalchemy.sql.func. So for example, using SQLAlchemy over a Postgres back end, and a table my_table(foo varchar(30), when timestamp) I might do something like</p>
<pre><code>my_table = metadata.tables['my_table']
foo = my_table.c['foo']
the_date = func.date_trunc('month', my_table.c['when'])
stmt = select(foo, the_date).group_by(the_date)
engine.execute(stmt)
</code></pre>
<p>To group by date truncated to month. But keep in mind that in that example, date_trunc() is a Postgres datetime function. Other databases will be different. You didn't mention the underlyig database. If there's a database independent way to do it I've never found one. In my case I run production and test aginst Postgres and unit tests aginst SQLite and have resorted to using SQLite user defined functions in my unit tests to emulate Postgress datetime functions. </p>
| 4 | 2008-10-20T16:05:14Z | [
"python",
"sql",
"sqlalchemy"
] |
In Python, what does it mean if an object is subscriptable or not? | 216,972 | <p>Which types of objects fall into the domain of "subscriptable"?</p>
| 109 | 2008-10-19T21:08:23Z | 216,980 | <p>It basically means that the object implements the <code>__getitem__()</code> method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes lists, tuples, and dictionaries.</p>
| 102 | 2008-10-19T21:11:05Z | [
"python",
"terminology"
] |
In Python, what does it mean if an object is subscriptable or not? | 216,972 | <p>Which types of objects fall into the domain of "subscriptable"?</p>
| 109 | 2008-10-19T21:08:23Z | 217,049 | <p>A scriptable object is an object that records the operations done to it and it can store them as a "script" which can be replayed.</p>
<p>For example, see: <a href="https://svn.enthought.com/enthought/browser/AppTools/trunk/docs/source/appscripting/Introduction.rst">Application Scripting Framework</a></p>
<p>Now, if Alistair didn't know what he asked and really meant "subscriptable" objects (as edited by others), then (as mipadi also answered) this is the correct one:</p>
<p>A subscriptable object is any object that implements the <code>__getitem__</code> special method (think lists, dictionaries).</p>
| 5 | 2008-10-19T22:05:30Z | [
"python",
"terminology"
] |
In Python, what does it mean if an object is subscriptable or not? | 216,972 | <p>Which types of objects fall into the domain of "subscriptable"?</p>
| 109 | 2008-10-19T21:08:23Z | 217,081 | <p>Off the top of my head, the following are the only built-ins that are subscriptable:</p>
<pre><code>string: "foobar"[3] == "b"
tuple: (1,2,3,4)[3] == 4
list: [1,2,3,4][3] == 4
dict: {"a":1, "b":2, "c":3}["c"] == 3
</code></pre>
<p>But mipadi's answer is correct; any class that implements __getitem__ is subscriptable</p>
| 20 | 2008-10-19T22:39:47Z | [
"python",
"terminology"
] |
Python/editline on OS X: £ sign seems to be bound to ed-prev-word | 217,020 | <p>On Mac OS X I canât enter a pound sterling sign (£) into the Python interactive shell.</p>
<pre><code>* Mac OS X 10.5.5
* Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17)
* European keyboard (£ is shift-3)
</code></pre>
<p>When I type shift-3 in the Python interactive shell, I seem to invoke the previous word function, i.e. the cursor will move to the start of the last âwordâ (i.e. space-delimited item) typed on the line. When Iâm back in the bash shell, typing shift-3 just produces a £, as expected.</p>
<p>This version of Python apparently uses editline for its interactive shell, as opposed to readline. Iâm guessing that one of the default editline key bindings binds shift-3 (or whatever editline sees when I type shift-3) to the ed-prev-word command.</p>
<p>Iâve tried a few things in my ~/.editrc file to remove this binding, and they donât have any effect:</p>
<ul>
<li><code>bind -r £</code></li>
<li><code>bind -r \243</code></li>
<li><code>bind -r \156</code></li>
</ul>
<p>And another that causes a bus error:</p>
<ul>
<li><code>bind £ \243</code></li>
</ul>
<p>Any ideas?</p>
| 0 | 2008-10-19T21:33:45Z | 217,036 | <p>This may be an editline issue; libedit may not accept UTF-8 characters:</p>
<ul>
<li><a href="http://tracker.firebirdsql.org/browse/CORE-362#action_11593" rel="nofollow">http://tracker.firebirdsql.org/browse/CORE-362#action_11593</a></li>
<li><a href="http://marc.info/?t=119056021900002&r=1&w=2" rel="nofollow">http://marc.info/?t=119056021900002&r=1&w=2</a></li>
</ul>
| 1 | 2008-10-19T21:54:07Z | [
"python",
"osx",
"unix",
"terminal",
"editline"
] |
How can I determine the display idle time from Python in Windows, Linux, and MacOS? | 217,157 | <p>I would like to know how long it's been since the user last hit a key or moved the mouse - not just in my application, but on the whole "computer" (i.e. display), in order to guess whether they're still at the computer and able to observe notifications that pop up on the screen.</p>
<p>I'd like to do this purely from (Py)GTK+, but I am amenable to calling platform-specific functions. Ideally I'd like to call functions which have already been wrapped from Python, but if that's not possible, I'm not above a little bit of C or <code>ctypes</code> code, as long as I know what I'm actually looking for.</p>
<p>On Windows I think the function I want is <a href="http://msdn.microsoft.com/en-us/library/ms646302.aspx"><code>GetLastInputInfo</code></a>, but that doesn't seem to be wrapped by pywin32; I hope I'm missing something.</p>
| 15 | 2008-10-19T23:25:08Z | 217,304 | <p>I got an answer regarding mouse-clicks suggesting to use <a href="http://www.cs.unc.edu/Research/assist/developer.shtml" rel="nofollow">pyHook</a>:</p>
<p><a href="http://stackoverflow.com/questions/165495/detecting-mouse-clicks-in-windows-using-python">http://stackoverflow.com/questions/165495/detecting-mouse-clicks-in-windows-using-python</a></p>
<p>Here's some other code I did to detect mouse-position via ctypes:
<a href="http://monkut.webfactional.com/blog/archive/2008/10/2/python-win-mouse-position" rel="nofollow">http://monkut.webfactional.com/blog/archive/2008/10/2/python-win-mouse-position</a></p>
<p>A more round-about method to accomplish this would be via screen capture and comparing any change in images using PIL.</p>
<p><a href="http://www.wellho.net/forum/Programming-in-Python-and-Ruby/Python-Imaging-Library-PIL.html" rel="nofollow">http://www.wellho.net/forum/Programming-in-Python-and-Ruby/Python-Imaging-Library-PIL.html</a></p>
| 2 | 2008-10-20T01:27:38Z | [
"python",
"winapi",
"gtk",
"pygtk",
"pywin32"
] |
How can I determine the display idle time from Python in Windows, Linux, and MacOS? | 217,157 | <p>I would like to know how long it's been since the user last hit a key or moved the mouse - not just in my application, but on the whole "computer" (i.e. display), in order to guess whether they're still at the computer and able to observe notifications that pop up on the screen.</p>
<p>I'd like to do this purely from (Py)GTK+, but I am amenable to calling platform-specific functions. Ideally I'd like to call functions which have already been wrapped from Python, but if that's not possible, I'm not above a little bit of C or <code>ctypes</code> code, as long as I know what I'm actually looking for.</p>
<p>On Windows I think the function I want is <a href="http://msdn.microsoft.com/en-us/library/ms646302.aspx"><code>GetLastInputInfo</code></a>, but that doesn't seem to be wrapped by pywin32; I hope I'm missing something.</p>
| 15 | 2008-10-19T23:25:08Z | 1,145,688 | <p><a href="http://www.gajim.org/" rel="nofollow">Gajim</a> does it this way on Windows, OS X and GNU/Linux (and other *nixes):</p>
<ol>
<li><a href="https://trac.gajim.org/browser/src/common/sleepy.py?rev=604c5de0dfe72dfa76b3014c410a50daae381cbe" rel="nofollow">Python wrapper module</a> (also includes Windows idle time detection code, using <code>GetTickCount</code> with <code>ctypes</code>);</li>
<li><a href="https://trac.gajim.org/browser/src/common/idle.py?rev=604c5de0dfe72dfa76b3014c410a50daae381cbe" rel="nofollow">Ctypes-based module to get X11 idle time</a> (using <code>XScreenSaverQueryInfo</code>, was a C module in old Gajim versions);</li>
<li><a href="https://trac.gajim.org/browser/src/osx/idle.c?rev=604c5de0dfe72dfa76b3014c410a50daae381cbe" rel="nofollow">C module to get OS X idle time</a> (using <code>HIDIdleTime</code> system property).</li>
</ol>
<p>Those links are to quite dated 0.12 version, so you may want to check current source for possible further improvements and changes.</p>
| 10 | 2009-07-17T21:07:04Z | [
"python",
"winapi",
"gtk",
"pygtk",
"pywin32"
] |
How can I determine the display idle time from Python in Windows, Linux, and MacOS? | 217,157 | <p>I would like to know how long it's been since the user last hit a key or moved the mouse - not just in my application, but on the whole "computer" (i.e. display), in order to guess whether they're still at the computer and able to observe notifications that pop up on the screen.</p>
<p>I'd like to do this purely from (Py)GTK+, but I am amenable to calling platform-specific functions. Ideally I'd like to call functions which have already been wrapped from Python, but if that's not possible, I'm not above a little bit of C or <code>ctypes</code> code, as long as I know what I'm actually looking for.</p>
<p>On Windows I think the function I want is <a href="http://msdn.microsoft.com/en-us/library/ms646302.aspx"><code>GetLastInputInfo</code></a>, but that doesn't seem to be wrapped by pywin32; I hope I'm missing something.</p>
| 15 | 2008-10-19T23:25:08Z | 16,777,652 | <p>If you use PyGTK and X11 on Linux, you can do something like this, which is based on what Pidgin does:</p>
<pre><code>import ctypes
import ctypes.util
import platform
class XScreenSaverInfo(ctypes.Structure):
_fields_ = [('window', ctypes.c_long),
('state', ctypes.c_int),
('kind', ctypes.c_int),
('til_or_since', ctypes.c_ulong),
('idle', ctypes.c_ulong),
('eventMask', ctypes.c_ulong)]
class IdleXScreenSaver(object):
def __init__(self):
self.xss = self._get_library('Xss')
self.gdk = self._get_library('gdk-x11-2.0')
self.gdk.gdk_display_get_default.restype = ctypes.c_void_p
# GDK_DISPLAY_XDISPLAY expands to gdk_x11_display_get_xdisplay
self.gdk.gdk_x11_display_get_xdisplay.restype = ctypes.c_void_p
self.gdk.gdk_x11_display_get_xdisplay.argtypes = [ctypes.c_void_p]
# GDK_ROOT_WINDOW expands to gdk_x11_get_default_root_xwindow
self.gdk.gdk_x11_get_default_root_xwindow.restype = ctypes.c_void_p
self.xss.XScreenSaverAllocInfo.restype = ctypes.POINTER(XScreenSaverInfo)
self.xss.XScreenSaverQueryExtension.restype = ctypes.c_int
self.xss.XScreenSaverQueryExtension.argtypes = [ctypes.c_void_p,
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
self.xss.XScreenSaverQueryInfo.restype = ctypes.c_int
self.xss.XScreenSaverQueryInfo.argtypes = [ctypes.c_void_p,
ctypes.c_void_p,
ctypes.POINTER(XScreenSaverInfo)]
# gtk_init() must have been called for this to work
import gtk
gtk # pyflakes
# has_extension = XScreenSaverQueryExtension(GDK_DISPLAY_XDISPLAY(gdk_display_get_default()),
# &event_base, &error_base);
event_base = ctypes.c_int()
error_base = ctypes.c_int()
gtk_display = self.gdk.gdk_display_get_default()
self.dpy = self.gdk.gdk_x11_display_get_xdisplay(gtk_display)
available = self.xss.XScreenSaverQueryExtension(self.dpy,
ctypes.byref(event_base),
ctypes.byref(error_base))
if available == 1:
self.xss_info = self.xss.XScreenSaverAllocInfo()
else:
self.xss_info = None
def _get_library(self, libname):
path = ctypes.util.find_library(libname)
if not path:
raise ImportError('Could not find library "%s"' % (libname, ))
lib = ctypes.cdll.LoadLibrary(path)
assert lib
return lib
def get_idle(self):
if not self.xss_info:
return 0
# XScreenSaverQueryInfo(GDK_DISPLAY_XDISPLAY(gdk_display_get_default()),
# GDK_ROOT_WINDOW(), mit_info);
drawable = self.gdk.gdk_x11_get_default_root_xwindow()
self.xss.XScreenSaverQueryInfo(self.dpy, drawable, self.xss_info)
# return (mit_info->idle) / 1000;
return self.xss_info.contents.idle / 1000
</code></pre>
<p>The example above uses gdk via ctypes to be able to access the X11 specific. Xscreensaver APIs also need to be accessed via ctypes.</p>
<p>It should be pretty easy to port it to use PyGI and introspection.</p>
| 4 | 2013-05-27T17:06:43Z | [
"python",
"winapi",
"gtk",
"pygtk",
"pywin32"
] |
Troubleshooting py2exe packaging problem | 217,666 | <p>I've written a setup.py script for py2exe, generated an executable for my python GUI application and I have a whole bunch of files in the dist directory, including the app, w9xopen.exe and MSVCR71.dll. When I try to run the application, I get an error message that just says "see the logfile for details". The only problem is, the log file is empty. </p>
<p>The closest error I've seen is "The following modules appear to be missing" but I'm not using any of those modules as far as I know (especially since they seem to be of databases I'm not using) but digging up on Google suggests that these are relatively benign warnings.</p>
<p>I've written and packaged a console application as well as a wxpython one with py2exe and both applications have compiled and run successfully. I am using a new python toolkit called dabo, which in turn makes uses of wxpython modules so I can't figure out what I'm doing wrong. Where do I start investigating the problem since obviously the log file hasn't been too useful? </p>
<p><b>Edit 1:</b>
The python version is 2.5. py2exe is 0.6.8. There were no significant build errors. The only one was the bit about "The following modules appear to be missing..." which were non critical errors since the packages listed were ones I was definitely not using and shouldn't stop the execution of the app either. Running the executable produced a logfile which was completely empty. Previously it had an error about locales which I've since fixed but clearly something is wrong as the executable wasn't running. The setup.py file is based quite heavily on the original setup.py generated by running their "app wizard" and looking at the example that Ed Leafe and some others posted. Yes, I have a log file and it's not printing anything for me to use, which is why I'm asking if there's any other troubleshooting avenue I've missed which will help me find out what's going on. </p>
<p>I have even written a bare bones test application which simply produces a bare bones GUI - an empty frame with some default menu options. The code written itself is only 3 lines and the rest is in the 3rd party toolkit. Again, that compiled into an exe (as did my original app) but simply did not run. There were no error output in the run time log file either. </p>
<p><b>Edit 2:</b>
It turns out that switching from "windows" to "console" for initial debugging purposes was insightful. I've now got a basic running test app and on to compiling the real app! </p>
<p><i>The test app:</i></p>
<pre>
import dabo
app = dabo.dApp()
app.start()
</pre>
<p><i>The setup.py for test app:</i></p>
<pre>
import os
import sys
import glob
from distutils.core import setup
import py2exe
import dabo.icons
daboDir = os.path.split(dabo.__file__)[0]
# Find the location of the dabo icons:
iconDir = os.path.split(dabo.icons.__file__)[0]
iconSubDirs = []
def getIconSubDir(arg, dirname, fnames):
if ".svn" not in dirname and dirname[-1] != "\\":
icons = glob.glob(os.path.join(dirname, "*.png"))
if icons:
subdir = (os.path.join("resources", dirname[len(arg)+1:]), icons)
iconSubDirs.append(subdir)
os.path.walk(iconDir, getIconSubDir, iconDir)
# locales:
localeDir = "%s%slocale" % (daboDir, os.sep)
locales = []
def getLocales(arg, dirname, fnames):
if ".svn" not in dirname and dirname[-1] != "\\":
mo_files = tuple(glob.glob(os.path.join(dirname, "*.mo")))
if mo_files:
subdir = os.path.join("dabo.locale", dirname[len(arg)+1:])
locales.append((subdir, mo_files))
os.path.walk(localeDir, getLocales, localeDir)
data_files=[("resources", glob.glob(os.path.join(iconDir, "*.ico"))),
("resources", glob.glob("resources/*"))]
data_files.extend(iconSubDirs)
data_files.extend(locales)
setup(name="basicApp",
version='0.01',
description="Test Dabo Application",
options={"py2exe": {
"compressed": 1, "optimize": 2, "bundle_files": 1,
"excludes": ["Tkconstants","Tkinter","tcl",
"_imagingtk", "PIL._imagingtk",
"ImageTk", "PIL.ImageTk", "FixTk", "kinterbasdb",
"MySQLdb", 'Numeric', 'OpenGL.GL', 'OpenGL.GLUT',
'dbGadfly', 'email.Generator',
'email.Iterators', 'email.Utils', 'kinterbasdb',
'numarray', 'pymssql', 'pysqlite2', 'wx.BitmapFromImage'],
"includes": ["encodings", "locale", "wx.gizmos","wx.lib.calendar"]}},
zipfile=None,
windows=[{'script':'basicApp.py'}],
data_files=data_files
)
</pre>
| 5 | 2008-10-20T06:46:22Z | 218,263 | <p>You may need to fix log handling first, <a href="http://www.py2exe.org/index.cgi/StderrLog" rel="nofollow">this</a> URL may help.</p>
<p>Later you may look for answer <a href="http://www.py2exe.org/index.cgi/GeneralTipsAndTricks" rel="nofollow">here</a>.</p>
<p>My answer is very general because you didn't give any more specific info (like py2exe/python version, py2exe log, other used 3rd party libraries).</p>
| 1 | 2008-10-20T12:33:37Z | [
"python",
"user-interface",
"py2exe"
] |
Troubleshooting py2exe packaging problem | 217,666 | <p>I've written a setup.py script for py2exe, generated an executable for my python GUI application and I have a whole bunch of files in the dist directory, including the app, w9xopen.exe and MSVCR71.dll. When I try to run the application, I get an error message that just says "see the logfile for details". The only problem is, the log file is empty. </p>
<p>The closest error I've seen is "The following modules appear to be missing" but I'm not using any of those modules as far as I know (especially since they seem to be of databases I'm not using) but digging up on Google suggests that these are relatively benign warnings.</p>
<p>I've written and packaged a console application as well as a wxpython one with py2exe and both applications have compiled and run successfully. I am using a new python toolkit called dabo, which in turn makes uses of wxpython modules so I can't figure out what I'm doing wrong. Where do I start investigating the problem since obviously the log file hasn't been too useful? </p>
<p><b>Edit 1:</b>
The python version is 2.5. py2exe is 0.6.8. There were no significant build errors. The only one was the bit about "The following modules appear to be missing..." which were non critical errors since the packages listed were ones I was definitely not using and shouldn't stop the execution of the app either. Running the executable produced a logfile which was completely empty. Previously it had an error about locales which I've since fixed but clearly something is wrong as the executable wasn't running. The setup.py file is based quite heavily on the original setup.py generated by running their "app wizard" and looking at the example that Ed Leafe and some others posted. Yes, I have a log file and it's not printing anything for me to use, which is why I'm asking if there's any other troubleshooting avenue I've missed which will help me find out what's going on. </p>
<p>I have even written a bare bones test application which simply produces a bare bones GUI - an empty frame with some default menu options. The code written itself is only 3 lines and the rest is in the 3rd party toolkit. Again, that compiled into an exe (as did my original app) but simply did not run. There were no error output in the run time log file either. </p>
<p><b>Edit 2:</b>
It turns out that switching from "windows" to "console" for initial debugging purposes was insightful. I've now got a basic running test app and on to compiling the real app! </p>
<p><i>The test app:</i></p>
<pre>
import dabo
app = dabo.dApp()
app.start()
</pre>
<p><i>The setup.py for test app:</i></p>
<pre>
import os
import sys
import glob
from distutils.core import setup
import py2exe
import dabo.icons
daboDir = os.path.split(dabo.__file__)[0]
# Find the location of the dabo icons:
iconDir = os.path.split(dabo.icons.__file__)[0]
iconSubDirs = []
def getIconSubDir(arg, dirname, fnames):
if ".svn" not in dirname and dirname[-1] != "\\":
icons = glob.glob(os.path.join(dirname, "*.png"))
if icons:
subdir = (os.path.join("resources", dirname[len(arg)+1:]), icons)
iconSubDirs.append(subdir)
os.path.walk(iconDir, getIconSubDir, iconDir)
# locales:
localeDir = "%s%slocale" % (daboDir, os.sep)
locales = []
def getLocales(arg, dirname, fnames):
if ".svn" not in dirname and dirname[-1] != "\\":
mo_files = tuple(glob.glob(os.path.join(dirname, "*.mo")))
if mo_files:
subdir = os.path.join("dabo.locale", dirname[len(arg)+1:])
locales.append((subdir, mo_files))
os.path.walk(localeDir, getLocales, localeDir)
data_files=[("resources", glob.glob(os.path.join(iconDir, "*.ico"))),
("resources", glob.glob("resources/*"))]
data_files.extend(iconSubDirs)
data_files.extend(locales)
setup(name="basicApp",
version='0.01',
description="Test Dabo Application",
options={"py2exe": {
"compressed": 1, "optimize": 2, "bundle_files": 1,
"excludes": ["Tkconstants","Tkinter","tcl",
"_imagingtk", "PIL._imagingtk",
"ImageTk", "PIL.ImageTk", "FixTk", "kinterbasdb",
"MySQLdb", 'Numeric', 'OpenGL.GL', 'OpenGL.GLUT',
'dbGadfly', 'email.Generator',
'email.Iterators', 'email.Utils', 'kinterbasdb',
'numarray', 'pymssql', 'pysqlite2', 'wx.BitmapFromImage'],
"includes": ["encodings", "locale", "wx.gizmos","wx.lib.calendar"]}},
zipfile=None,
windows=[{'script':'basicApp.py'}],
data_files=data_files
)
</pre>
| 5 | 2008-10-20T06:46:22Z | 218,432 | <p>See <a href="http://www.wxpython.org/docs/api/wx.App-class.html" rel="nofollow">http://www.wxpython.org/docs/api/wx.App-class.html</a> for wxPyton's <code>App</code> class initializer. If you want to run the app from a console and have stderr print to there, then supply <code>False</code> for the <code>redirect</code> argument. Otherwise, if you just want a window to pop up, set <code>redirect</code> to <code>True</code> and <code>filename</code> to <code>None</code>.</p>
| 1 | 2008-10-20T13:31:21Z | [
"python",
"user-interface",
"py2exe"
] |
String Simple Substitution | 217,881 | <p>What's the easiest way of me converting the simpler regex format that most users are used to into the correct re python regex string?</p>
<p>As an example, I need to convert this:</p>
<pre><code>string = "*abc+de?"
</code></pre>
<p>to this:</p>
<pre><code>string = ".*abc.+de.?"
</code></pre>
<p>Of course I could loop through the string and build up another string character by character, but that's surely an inefficient way of doing this?</p>
| 0 | 2008-10-20T09:27:08Z | 217,896 | <p>I'd use <a href="http://www.python.org/doc/2.5.2/lib/string-methods.html#l2h-255" rel="nofollow"><code>replace</code></a>:</p>
<pre><code>def wildcard_to_regex(str):
return str.replace("*", ".*").replace("?", .?").replace("#", "\d")
</code></pre>
<p>This probably isn't the most efficient way but it should be efficient enough for most purposes. Notice that some wildcard formats allow character classes which are more difficult to handle.</p>
| 0 | 2008-10-20T09:35:04Z | [
"python",
"string"
] |
String Simple Substitution | 217,881 | <p>What's the easiest way of me converting the simpler regex format that most users are used to into the correct re python regex string?</p>
<p>As an example, I need to convert this:</p>
<pre><code>string = "*abc+de?"
</code></pre>
<p>to this:</p>
<pre><code>string = ".*abc.+de.?"
</code></pre>
<p>Of course I could loop through the string and build up another string character by character, but that's surely an inefficient way of doing this?</p>
| 0 | 2008-10-20T09:27:08Z | 217,916 | <p>Here is a <a href="http://www.unix.com.ua/orelly/perl/cookbook/ch06_10.htm" rel="nofollow">Perl example</a> of doing this. It is simply using a table to replace each wildcard construct with the corresponding regular expression. I've done this myself previously, but in C. It shouldn't be too hard to port to Python.</p>
| 0 | 2008-10-20T09:44:38Z | [
"python",
"string"
] |
String Simple Substitution | 217,881 | <p>What's the easiest way of me converting the simpler regex format that most users are used to into the correct re python regex string?</p>
<p>As an example, I need to convert this:</p>
<pre><code>string = "*abc+de?"
</code></pre>
<p>to this:</p>
<pre><code>string = ".*abc.+de.?"
</code></pre>
<p>Of course I could loop through the string and build up another string character by character, but that's surely an inefficient way of doing this?</p>
| 0 | 2008-10-20T09:27:08Z | 217,933 | <p>You'll probably only be doing this substitution occasionally, such as each time a user enters a new search string, so I wouldn't worry about how efficient the solution is.</p>
<p>You need to generate a list of the replacements you need to convert from the "user format" to a regex. For ease of maintenance I would store these in a dictionary, and like @Konrad Rudolph I would just use the replace method:</p>
<pre><code>def wildcard_to_regex(wildcard):
replacements = {
'*': '.*',
'?': '.?',
'+': '.+',
}
regex = wildcard
for (wildcard_pattern, regex_pattern) in replacements.items():
regex = regex.replace(wildcard_pattern, regex_pattern)
return regex
</code></pre>
<p>Note that this only works for simple character replacements, although other complex code can at least be hidden in the <code>wildcard_to_regex</code> function if necessary. </p>
<p>(Also, I'm not sure that <code>?</code> should translate to <code>.?</code> -- I think normal wildcards have <code>?</code> as "exactly one character", so its replacement should be a simple <code>.</code> -- but I'm following your example.)</p>
| 1 | 2008-10-20T09:51:47Z | [
"python",
"string"
] |
String Simple Substitution | 217,881 | <p>What's the easiest way of me converting the simpler regex format that most users are used to into the correct re python regex string?</p>
<p>As an example, I need to convert this:</p>
<pre><code>string = "*abc+de?"
</code></pre>
<p>to this:</p>
<pre><code>string = ".*abc.+de.?"
</code></pre>
<p>Of course I could loop through the string and build up another string character by character, but that's surely an inefficient way of doing this?</p>
| 0 | 2008-10-20T09:27:08Z | 217,978 | <p>.replacing() each of the wildcards is the quick way, but what if the wildcarded string contains other regex special characters? eg. someone searching for 'my.thing*' probably doesn't mean that '.' to match any character. And in the worst case things like match-group-creating parentheses are likely to break your final handling of the regex matches.</p>
<p>re.escape can be used to put literal characters into regexes. You'll have to split out the wildcard characters first though. The usual trick for that is to use re.split with a matching bracket, resulting in a list in the form [literal, wildcard, literal, wildcard, literal...].</p>
<p>Example code:</p>
<pre><code>wildcards= re.compile('([?*+])')
escapewild= {'?': '.', '*': '.*', '+': '.+'}
def escapePart((parti, part)):
if parti%2==0: # even items are literals
return re.escape(part)
else: # odd items are wildcards
return escapewild[part]
def convertWildcardedToRegex(s):
parts= map(escapePart, enumerate(wildcards.split(s)))
return '^%s$' % (''.join(parts))
</code></pre>
| 2 | 2008-10-20T10:13:13Z | [
"python",
"string"
] |
String Simple Substitution | 217,881 | <p>What's the easiest way of me converting the simpler regex format that most users are used to into the correct re python regex string?</p>
<p>As an example, I need to convert this:</p>
<pre><code>string = "*abc+de?"
</code></pre>
<p>to this:</p>
<pre><code>string = ".*abc.+de.?"
</code></pre>
<p>Of course I could loop through the string and build up another string character by character, but that's surely an inefficient way of doing this?</p>
| 0 | 2008-10-20T09:27:08Z | 218,102 | <p>Those don't look like regexps you're trying to translate, they look more like unix shell globs. Python has a <a href="http://www.python.org/doc/2.5.2/lib/module-fnmatch.html" rel="nofollow">module</a> for doing this already. It doesn't know about the "+" syntax you used, but neither does my shell, and I think the syntax is nonstandard.</p>
<pre><code>>>> import fnmatch
>>> fnmatch.fnmatch("fooabcdef", "*abcde?")
True
>>> help(fnmatch.fnmatch)
Help on function fnmatch in module fnmatch:
fnmatch(name, pat)
Test whether FILENAME matches PATTERN.
Patterns are Unix shell style:
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any char not in seq
An initial period in FILENAME is not special.
Both FILENAME and PATTERN are first case-normalized
if the operating system requires it.
If you don't want this, use fnmatchcase(FILENAME, PATTERN).
>>>
</code></pre>
| 5 | 2008-10-20T11:29:13Z | [
"python",
"string"
] |
how to generate unit test code for methods | 217,900 | <p>i want to write code for unit test to test my application code. I have different methods and now want to test these methods one by one in python script.
but i do not how to i write. can any one give me example of small code for unit testing in python.
i am thankful </p>
| 3 | 2008-10-20T09:36:51Z | 217,925 | <p>Read the <a href="http://www.python.org/doc/2.5.2/lib/module-unittest.html" rel="nofollow">unit testing framework section</a> of the <a href="http://www.python.org/doc/2.5.2/lib/lib.html" rel="nofollow">Python Library Reference</a>.</p>
<p>A <a href="http://www.python.org/doc/2.5.2/lib/minimal-example.html" rel="nofollow">basic example</a> from the documentation:</p>
<pre><code>import random
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def testshuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
def testchoice(self):
element = random.choice(self.seq)
self.assert_(element in self.seq)
def testsample(self):
self.assertRaises(ValueError, random.sample, self.seq, 20)
for element in random.sample(self.seq, 5):
self.assert_(element in self.seq)
if __name__ == '__main__':
unittest.main()
</code></pre>
| 7 | 2008-10-20T09:48:11Z | [
"python",
"unit-testing"
] |
how to generate unit test code for methods | 217,900 | <p>i want to write code for unit test to test my application code. I have different methods and now want to test these methods one by one in python script.
but i do not how to i write. can any one give me example of small code for unit testing in python.
i am thankful </p>
| 3 | 2008-10-20T09:36:51Z | 217,930 | <p>Here's an <a href="http://www.python.org/doc/2.5.2/lib/minimal-example.html" rel="nofollow">example</a> and you might want to read a little more on <a href="http://www.python.org/doc/2.5.2/lib/module-unittest.html" rel="nofollow">pythons unit testing</a>.</p>
| 1 | 2008-10-20T09:49:29Z | [
"python",
"unit-testing"
] |
how to generate unit test code for methods | 217,900 | <p>i want to write code for unit test to test my application code. I have different methods and now want to test these methods one by one in python script.
but i do not how to i write. can any one give me example of small code for unit testing in python.
i am thankful </p>
| 3 | 2008-10-20T09:36:51Z | 218,489 | <p>It's probably best to start off with the given <code>unittest</code> example. Some standard best practices: </p>
<ul>
<li>put all your tests in a <code>tests</code> folder at the root of your project.</li>
<li>write one test module for each python module you're testing.</li>
<li>test modules should start with the word <code>test</code>.</li>
<li>test methods should start with the word <code>test</code>. </li>
</ul>
<p>When you've become comfortable with <code>unittest</code> (and it shouldn't take long), there are some nice extensions to it that will make life easier as your tests grow in number and scope:</p>
<ul>
<li><a href="http://somethingaboutorange.com/mrl/projects/nose/" rel="nofollow">nose</a> -- easily find and run all your tests, and more.</li>
<li><a href="http://testoob.sourceforge.net/" rel="nofollow">testoob</a> -- colorized output (and more, but that's why I use it).</li>
<li><a href="http://pythoscope.org/" rel="nofollow">pythoscope</a> -- haven't tried it, but this will automatically generate (failing) test stubs for your application. Should save a lot of time writing boilerplate code.</li>
</ul>
| 4 | 2008-10-20T13:46:52Z | [
"python",
"unit-testing"
] |
Getting method parameter names in python | 218,616 | <p>Given the python function:</p>
<pre><code>def aMethod(arg1, arg2):
pass
</code></pre>
<p>How can I extract the number and names of the arguments. Ie. given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2")</p>
<p>The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. Ie. how would the decorator look that printed "a,b" when I call aMethod("a","b")</p>
| 131 | 2008-10-20T14:22:02Z | 218,625 | <p>In CPython, the number of arguments is</p>
<pre><code>aMethod.func_code.co_argcount
</code></pre>
<p>and their names are in the beginning of</p>
<pre><code>aMethod.func_code.co_varnames
</code></pre>
<p>These are implementation details of CPython, so this probably does not work in other implementations of Python, such as IronPython and Jython.</p>
<p>One portable way to admit "pass-through" arguments is to define your function with the signature <code>func(*args, **kwargs)</code>. This is used a lot in e.g. matplotlib, where the outer API layer passes lots of keyword arguments to the lower-level API.</p>
| 73 | 2008-10-20T14:24:48Z | [
"python",
"decorator",
"introspection",
"python-datamodel"
] |
Getting method parameter names in python | 218,616 | <p>Given the python function:</p>
<pre><code>def aMethod(arg1, arg2):
pass
</code></pre>
<p>How can I extract the number and names of the arguments. Ie. given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2")</p>
<p>The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. Ie. how would the decorator look that printed "a,b" when I call aMethod("a","b")</p>
| 131 | 2008-10-20T14:22:02Z | 218,709 | <p>Take a look at the <a href="http://docs.python.org/library/inspect.html">inspect</a> module - this will do the inspection of the various code object properties for you.</p>
<pre><code>>>> inspect.getargspec(aMethod)
(['arg1', 'arg2'], None, None, None)
</code></pre>
<p>The other results are the name of the *args and **kwargs variables, and the defaults provided. ie.</p>
<pre><code>>>> def foo(a,b,c=4, *arglist, **keywords): pass
>>> inspect.getargspec(foo)
(['a', 'b', 'c'], 'arglist', 'keywords', (4,))
</code></pre>
| 240 | 2008-10-20T14:52:19Z | [
"python",
"decorator",
"introspection",
"python-datamodel"
] |
Getting method parameter names in python | 218,616 | <p>Given the python function:</p>
<pre><code>def aMethod(arg1, arg2):
pass
</code></pre>
<p>How can I extract the number and names of the arguments. Ie. given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2")</p>
<p>The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. Ie. how would the decorator look that printed "a,b" when I call aMethod("a","b")</p>
| 131 | 2008-10-20T14:22:02Z | 220,366 | <p>Here is something I think will work for what you want, using a decorator.</p>
<pre><code>class LogWrappedFunction(object):
def __init__(self, function):
self.function = function
def logAndCall(self, *arguments, **namedArguments):
print "Calling %s with arguments %s and named arguments %s" %\
(self.function.func_name, arguments, namedArguments)
self.function.__call__(*arguments, **namedArguments)
def logwrap(function):
return LogWrappedFunction(function).logAndCall
@logwrap
def doSomething(spam, eggs, foo, bar):
print "Doing something totally awesome with %s and %s." % (spam, eggs)
doSomething("beans","rice", foo="wiggity", bar="wack")
</code></pre>
<p>Run it, it will yield the following output:</p>
<pre><code>C:\scripts>python decoratorExample.py
Calling doSomething with arguments ('beans', 'rice') and named arguments {'foo':
'wiggity', 'bar': 'wack'}
Doing something totally awesome with beans and rice.
</code></pre>
| 10 | 2008-10-21T00:02:19Z | [
"python",
"decorator",
"introspection",
"python-datamodel"
] |
Getting method parameter names in python | 218,616 | <p>Given the python function:</p>
<pre><code>def aMethod(arg1, arg2):
pass
</code></pre>
<p>How can I extract the number and names of the arguments. Ie. given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2")</p>
<p>The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. Ie. how would the decorator look that printed "a,b" when I call aMethod("a","b")</p>
| 131 | 2008-10-20T14:22:02Z | 2,991,341 | <p>I think what you're looking for is the locals method - </p>
<pre><code>
In [6]: def test(a, b):print locals()
...:
In [7]: test(1,2)
{'a': 1, 'b': 2}
</code></pre>
| 9 | 2010-06-07T16:37:20Z | [
"python",
"decorator",
"introspection",
"python-datamodel"
] |
Getting method parameter names in python | 218,616 | <p>Given the python function:</p>
<pre><code>def aMethod(arg1, arg2):
pass
</code></pre>
<p>How can I extract the number and names of the arguments. Ie. given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2")</p>
<p>The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. Ie. how would the decorator look that printed "a,b" when I call aMethod("a","b")</p>
| 131 | 2008-10-20T14:22:02Z | 16,542,145 | <p>In a decorator method, you can list arguments of the original method in this way:</p>
<pre><code>import inspect, itertools
def my_decorator():
def decorator(f):
def wrapper(*args, **kwargs):
# if you want arguments names as a list:
args_name = inspect.getargspec(f)[0]
print(args_name)
# if you want names and values as a dictionary:
args_dict = dict(itertools.izip(args_name, args))
print(args_dict)
# if you want values as a list:
args_values = args_dict.values()
print(args_values)
</code></pre>
<p>If the <code>**kwargs</code> are important for you, then it will be a bit complicated:</p>
<pre><code> def wrapper(*args, **kwargs):
args_name = list(OrderedDict.fromkeys(inspect.getargspec(f)[0] + kwargs.keys()))
args_dict = OrderedDict(list(itertools.izip(args_name, args)) + list(kwargs.iteritems()))
args_values = args_dict.values()
</code></pre>
<p>Example:</p>
<pre><code>@my_decorator()
def my_function(x, y, z=3):
pass
my_function(1, y=2, z=3, w=0)
# prints:
# ['x', 'y', 'z', 'w']
# {'y': 2, 'x': 1, 'z': 3, 'w': 0}
# [1, 2, 3, 0]
</code></pre>
| 11 | 2013-05-14T11:36:45Z | [
"python",
"decorator",
"introspection",
"python-datamodel"
] |
How do you share data between a parent and forked child process in Python? | 218,935 | <p>I'm pretty sure one would do this using the os.plock(op) function, but I have no idea how. Also, if there's a better way, I'd be grateful to find out. Code snippets are very welcome. </p>
| 10 | 2008-10-20T15:57:05Z | 218,943 | <p>This is pretty much Python-independent! It's a classic example of Unix interprocess communication. One good option is to use <code>popen()</code> to open a pipe between the parent and child processes, and pass data/messages back and forth along the pipe.</p>
<p>Take a look at the <a href="http://www.python.org/doc/2.5.2/lib/module-subprocess.html" rel="nofollow"><code>subprocess</code> module</a>, which can set up the necessary pipes automatically while spawning child processes.</p>
| 4 | 2008-10-20T15:59:25Z | [
"python",
"fork",
"share"
] |
How do you share data between a parent and forked child process in Python? | 218,935 | <p>I'm pretty sure one would do this using the os.plock(op) function, but I have no idea how. Also, if there's a better way, I'd be grateful to find out. Code snippets are very welcome. </p>
| 10 | 2008-10-20T15:57:05Z | 218,970 | <p>You have two options: <code>os.popen*</code> in the <code>os</code> module, or you can use the <code>subprocess</code> module to the same effect. The Python manual has pretty documentation and examples for <a href="http://www.python.org/doc/2.5.2/lib/module-popen2.html" rel="nofollow" title="popen">popen</a> and <a href="http://www.python.org/doc/2.5.2/lib/module-subprocess.html" rel="nofollow" title="subprocess">subprocess</a>.</p>
| 1 | 2008-10-20T16:03:59Z | [
"python",
"fork",
"share"
] |
How do you share data between a parent and forked child process in Python? | 218,935 | <p>I'm pretty sure one would do this using the os.plock(op) function, but I have no idea how. Also, if there's a better way, I'd be grateful to find out. Code snippets are very welcome. </p>
| 10 | 2008-10-20T15:57:05Z | 219,048 | <p><a href="http://docs.python.org/library/subprocess">Subprocess</a> replaces os.popen, os.system, os.spawn, popen2 and commands. A <a href="http://docs.python.org/library/subprocess#replacing-shell-pipe-line">simple example for piping</a> would be:</p>
<pre><code>p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
</code></pre>
<p>You could also use a <a href="http://docs.python.org/library/mmap.html">memory mapped file</a> with the flag=MAP_SHARED for shared memory between processes.</p>
<p><a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> abstracts both <a href="http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes">pipes</a> and <a href="http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes">shared memory</a> and provides a higher level interface. Taken from the Processing documentation:</p>
<pre><code>from multiprocessing import Process, Pipe
def f(conn):
conn.send([42, None, 'hello'])
conn.close()
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p.start()
print parent_conn.recv() # prints "[42, None, 'hello']"
p.join()
</code></pre>
| 12 | 2008-10-20T16:26:05Z | [
"python",
"fork",
"share"
] |
How do you share data between a parent and forked child process in Python? | 218,935 | <p>I'm pretty sure one would do this using the os.plock(op) function, but I have no idea how. Also, if there's a better way, I'd be grateful to find out. Code snippets are very welcome. </p>
| 10 | 2008-10-20T15:57:05Z | 219,066 | <p>Take a look at the <a href="http://docs.python.org/dev/library/multiprocessing.html">multiprocessing</a> module new in python 2.6 (also available for earlier versions a <a href="http://pyprocessing.berlios.de/">pyprocessing</a></p>
<p>Here's an example from the docs illustrating passing information using a pipe for instance:</p>
<pre><code>from multiprocessing import Process, Pipe
def f(conn):
conn.send([42, None, 'hello'])
conn.close()
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p.start()
print parent_conn.recv() # prints "[42, None, 'hello']"
p.join()
</code></pre>
| 7 | 2008-10-20T16:30:34Z | [
"python",
"fork",
"share"
] |
how can i use sharepoint (via soap?) from python? | 218,987 | <p>I want to use Sharepoint with python (C-Python)</p>
<p>Has anyone tried this before ?</p>
| 9 | 2008-10-20T16:09:36Z | 219,175 | <p>SharePoint exposes several web services which you can use to query and update data.</p>
<p>I'm not sure what web service toolkits there are for Python but they should be able to build proxies for these services without any issues.</p>
<p>This article should give you enough information to get started.</p>
<p><a href="http://www.developer.com/tech/article.php/3104621" rel="nofollow">http://www.developer.com/tech/article.php/3104621</a></p>
| 3 | 2008-10-20T17:05:58Z | [
"python",
"sharepoint",
"soap",
"ntlm",
"suds"
] |
how can i use sharepoint (via soap?) from python? | 218,987 | <p>I want to use Sharepoint with python (C-Python)</p>
<p>Has anyone tried this before ?</p>
| 9 | 2008-10-20T16:09:36Z | 219,236 | <p>SOAP with Python is pretty easy. <a href="http://www.diveintopython.net/soap_web_services/index.html" rel="nofollow">Here's a tutorial</a> from Dive Into Python.</p>
| 4 | 2008-10-20T17:29:52Z | [
"python",
"sharepoint",
"soap",
"ntlm",
"suds"
] |
how can i use sharepoint (via soap?) from python? | 218,987 | <p>I want to use Sharepoint with python (C-Python)</p>
<p>Has anyone tried this before ?</p>
| 9 | 2008-10-20T16:09:36Z | 222,242 | <p>To get the wsdl :</p>
<pre><code>import sys
# we use suds -> https://fedorahosted.org/suds
from suds import WebFault
from suds.client import *
import urllib2
# my 2 url conf
# url_sharepoint,url_NTLM_authproxy
import myconfig as my
# build url
wsdl = '_vti_bin/SiteData.asmx?WSDL'
url = '/'.join([my.url_sharepoint,wsdl])
# we need a NTLM_auth_Proxy -> http://ntlmaps.sourceforge.net/
# follow instruction and get proxy running
proxy_handler = urllib2.ProxyHandler({'http': my.url_NTLM_authproxy })
opener = urllib2.build_opener(proxy_handler)
client = SoapClient(url, {'opener' : opener})
print client.wsdl
</code></pre>
<p>main (mean) problem:
the sharepoint-server uses a NTLM-Auth [ :-( ]
so i had to use the NTLM-Auth-Proxy</p>
<p>To Rob and Enzondio : THANKS for your hints !</p>
| 8 | 2008-10-21T15:13:46Z | [
"python",
"sharepoint",
"soap",
"ntlm",
"suds"
] |
how can i use sharepoint (via soap?) from python? | 218,987 | <p>I want to use Sharepoint with python (C-Python)</p>
<p>Has anyone tried this before ?</p>
| 9 | 2008-10-20T16:09:36Z | 5,403,203 | <p>I suspect that since this question was answered the SUDS library has been updated to take care of the required authentication itself. After jumping through various hoops, I found this to do the trick:</p>
<pre><code>
from suds import WebFault
from suds.client import *
from suds.transport.https import WindowsHttpAuthenticated
user = r'SERVER\user'
password = "yourpassword"
url = "http://sharepointserver/_vti_bin/SiteData.asmx?WSDL"
ntlm = WindowsHttpAuthenticated(username = user, password = password)
client = Client(url, transport=ntlm)
</code></pre>
| 9 | 2011-03-23T09:36:12Z | [
"python",
"sharepoint",
"soap",
"ntlm",
"suds"
] |
How Python web frameworks, WSGI and CGI fit together | 219,110 | <p>I have a <a href="http://en.wikipedia.org/wiki/Bluehost">Bluehost</a> account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in <code>.htaccess</code>:</p>
<pre><code>Options +ExecCGI
AddType text/html py
AddHandler cgi-script .py
</code></pre>
<p>Now, whenever I look up web programming with Python, I hear a lot about WSGI and how most frameworks use it. But I just don't understand how it all fits together, especially when my web server is given (Apache running at a host's machine) and not something I can really play with (except defining <code>.htaccess</code> commands).</p>
<p>How are <a href="http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface">WSGI</a>, CGI, and the frameworks all connected? What do I need to know, install, and do if I want to run a web framework (say <a href="http://webpy.org/">web.py</a> or <a href="http://en.wikipedia.org/wiki/CherryPy">CherryPy</a>) on my basic CGI configuration? How to install WSGI support?</p>
| 127 | 2008-10-20T16:43:57Z | 219,124 | <p>You can <a href="http://www.python.org/dev/peps/pep-0333/#the-server-gateway-side">run WSGI over CGI as Pep333 demonstrates</a> as an example. However every time there is a request a new Python interpreter is started and the whole context (database connections, etc.) needs to be build which all take time.</p>
<p>The best if you want to run WSGI would be if your host would install <a href="http://code.google.com/p/modwsgi/">mod_wsgi</a> and made an appropriate configuration to defer control to an application of yours.</p>
<p><a href="http://trac.saddi.com/flup">Flup</a> is another way to run with WSGI for any webserver that can speak <a href="http://www.fastcgi.com/drupal/">FCGI</a>, <a href="http://www.mems-exchange.org/software/scgi/">SCGI</a> or AJP. From my experience only FCGI really works, and it can be used in Apache either via <a href="http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html">mod_fastcgi</a> or if you can run a separate Python daemon with <a href="http://mproxyfcgi.sourceforge.net/">mod_proxy_fcgi</a>.</p>
<p><a href="http://wsgi.org">WSGI</a> is a protocol much like CGI, which defines a set of rules how webserver and Python code can interact, it is defined as <a href="http://www.python.org/dev/peps/pep-0333">Pep333</a>. It makes it possible that many different webservers can use many different frameworks and applications using the same application protocol. This is very beneficial and makes it so useful.</p>
| 21 | 2008-10-20T16:49:17Z | [
"python",
"apache",
"cgi",
"wsgi"
] |
How Python web frameworks, WSGI and CGI fit together | 219,110 | <p>I have a <a href="http://en.wikipedia.org/wiki/Bluehost">Bluehost</a> account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in <code>.htaccess</code>:</p>
<pre><code>Options +ExecCGI
AddType text/html py
AddHandler cgi-script .py
</code></pre>
<p>Now, whenever I look up web programming with Python, I hear a lot about WSGI and how most frameworks use it. But I just don't understand how it all fits together, especially when my web server is given (Apache running at a host's machine) and not something I can really play with (except defining <code>.htaccess</code> commands).</p>
<p>How are <a href="http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface">WSGI</a>, CGI, and the frameworks all connected? What do I need to know, install, and do if I want to run a web framework (say <a href="http://webpy.org/">web.py</a> or <a href="http://en.wikipedia.org/wiki/CherryPy">CherryPy</a>) on my basic CGI configuration? How to install WSGI support?</p>
| 127 | 2008-10-20T16:43:57Z | 505,534 | <p>I think <a href="http://stackoverflow.com/questions/219110/how-python-web-frameworks-wsgi-and-cgi-fit-together/219124#219124">Florian's answer</a> answers the part of your question about "what is WSGI", especially if you read <a href="http://www.python.org/dev/peps/pep-0333">the PEP</a>.</p>
<p>As for the questions you pose towards the end:</p>
<p>WSGI, CGI, FastCGI etc. are all protocols for a web server to <em>run code</em>, and deliver the dynamic content that is produced. Compare this to static web serving, where a plain HTML file is basically delivered as is to the client.</p>
<p><strong>CGI, FastCGI and SCGI are language agnostic.</strong> You can write CGI scripts in Perl, Python, C, bash, whatever. CGI defines <em>which</em> executable will be called, based on the URL, and <em>how</em> it will be called: the arguments and environment. It also defines how the return value should be passed back to the web server once your executable is finished. The variations are basically optimisations to be able to handle more requests, reduce latency and so on; the basic concept is the same.</p>
<p><strong>WSGI is Python only.</strong> Rather than a language agnostic protocol, a standard function signature is defined:</p>
<pre><code>def simple_app(environ, start_response):
"""Simplest possible application object"""
status = '200 OK'
response_headers = [('Content-type','text/plain')]
start_response(status, response_headers)
return ['Hello world!\n']
</code></pre>
<p>That is a complete (if limited) WSGI application. A web server with WSGI support (such as Apache with mod_wsgi) can invoke this function whenever a request arrives.</p>
<p>The reason this is so great is that we can avoid the messy step of converting from a HTTP GET/POST to CGI to Python, and back again on the way out. It's a much more direct, clean and efficient linkage.</p>
<p>It also makes it much easier to have long-running frameworks running behind web servers, if all that needs to be done for a request is a function call. With plain CGI, you'd have to <a href="http://tools.cherrypy.org/wiki/RunAsCGI">start your whole framework up</a> for each individual request.</p>
<p>To have WSGI support, you'll need to have installed a WSGI module (like <a href="http://code.google.com/p/modwsgi/">mod_wsgi</a>), or use a web server with WSGI baked in (like <a href="http://tools.cherrypy.org/">CherryPy</a>). If neither of those are possible, you <em>could</em> use the CGI-WSGI bridge given in the PEP.</p>
| 49 | 2009-02-03T00:04:46Z | [
"python",
"apache",
"cgi",
"wsgi"
] |
How Python web frameworks, WSGI and CGI fit together | 219,110 | <p>I have a <a href="http://en.wikipedia.org/wiki/Bluehost">Bluehost</a> account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in <code>.htaccess</code>:</p>
<pre><code>Options +ExecCGI
AddType text/html py
AddHandler cgi-script .py
</code></pre>
<p>Now, whenever I look up web programming with Python, I hear a lot about WSGI and how most frameworks use it. But I just don't understand how it all fits together, especially when my web server is given (Apache running at a host's machine) and not something I can really play with (except defining <code>.htaccess</code> commands).</p>
<p>How are <a href="http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface">WSGI</a>, CGI, and the frameworks all connected? What do I need to know, install, and do if I want to run a web framework (say <a href="http://webpy.org/">web.py</a> or <a href="http://en.wikipedia.org/wiki/CherryPy">CherryPy</a>) on my basic CGI configuration? How to install WSGI support?</p>
| 127 | 2008-10-20T16:43:57Z | 518,104 | <p>It's a simple abstraction layer for Python, akin to what the Servlet spec is for Java. Whereas CGI is really low level and just dumps stuff into the process environment and standard in/out, the above two specs model the http request and response as constructs in the language. My impression however is that in Python folks have not quite settled on de-facto implementations so you have a mix of reference implementations, and other utility-type libraries that provide other things along with WSGI support (e.g. Paste). Of course I could be wrong, I'm a newcomer to Python. The "web scripting" community is coming at the problem from a different direction (shared hosting, CGI legacy, privilege separation concerns) than Java folks had the luxury of starting with (running a single enterprise container in a dedicated environment against statically compiled and deployed code).</p>
| 4 | 2009-02-05T21:48:33Z | [
"python",
"apache",
"cgi",
"wsgi"
] |
How Python web frameworks, WSGI and CGI fit together | 219,110 | <p>I have a <a href="http://en.wikipedia.org/wiki/Bluehost">Bluehost</a> account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in <code>.htaccess</code>:</p>
<pre><code>Options +ExecCGI
AddType text/html py
AddHandler cgi-script .py
</code></pre>
<p>Now, whenever I look up web programming with Python, I hear a lot about WSGI and how most frameworks use it. But I just don't understand how it all fits together, especially when my web server is given (Apache running at a host's machine) and not something I can really play with (except defining <code>.htaccess</code> commands).</p>
<p>How are <a href="http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface">WSGI</a>, CGI, and the frameworks all connected? What do I need to know, install, and do if I want to run a web framework (say <a href="http://webpy.org/">web.py</a> or <a href="http://en.wikipedia.org/wiki/CherryPy">CherryPy</a>) on my basic CGI configuration? How to install WSGI support?</p>
| 127 | 2008-10-20T16:43:57Z | 520,194 | <p><strong>How WSGI, CGI, and the frameworks are all connected ?</strong></p>
<p>Apache listens on port 80. It gets an HTTP request. It parses the request to find a way to respond. Apache has a LOT of choices for responding. One way to respond is to use CGI to run a script. Another way to respond is to simply serve a file. </p>
<p>In the case of CGI, Apache prepares an environment and invokes the script through the CGI protocol. This is a standard Unix Fork/Exec situation -- the CGI subprocess inherits an OS environment including the socket and stdout. The CGI subprocess writes a response, which goes back to Apache; Apache sends this response to the browser.</p>
<p>CGI is primitive and annoying. Mostly because it forks a subprocess for every request, and subprocess must exit or close stdout and stderr to signify end of response.</p>
<p>WSGI is an interface that is based on the CGI design pattern. It is not necessarily CGI -- it does not have to fork a subprocess for each request. It can be CGI, but it doesn't have to be.</p>
<p>WSGI adds to the CGI design pattern in several important ways. It parses the HTTP Request Headers for you and adds these to the environment. It supplies any POST-oriented input as a file-like object in the environment. It also provides you a function that will formulate the response, saving you from a lot of formatting details.</p>
<p><strong>What do I need to know / install / do if I want to run a web framework (say web.py or cherrypy) on my basic CGI configuration ?</strong></p>
<p>Recall that forking a subprocess is expensive. There are two ways to work around this.</p>
<ol>
<li><p><strong>Embedded</strong> <code>mod_wsgi</code> or <code>mod_python</code> embeds Python inside Apache; no process is forked. Apache runs the Django application directly.</p></li>
<li><p><strong>Daemon</strong> <code>mod_wsgi</code> or <code>mod_fastcgi</code> allows Apache to interact with a separate daemon (or "long-running process"), using the WSGI protocol. You start your long-running Django process, then you configure Apache's mod_fastcgi to communicate with this process.</p></li>
</ol>
<p>Note that <code>mod_wsgi</code> can work in either mode: embedded or daemon.</p>
<p>When you read up on mod_fastcgi, you'll see that Django uses <a href="http://pypi.python.org/pypi/flup/">flup</a> to create a WSGI-compatible interface from the information provided by mod_fastcgi. The pipeline works like this.</p>
<pre><code>Apache -> mod_fastcgi -> FLUP (via FastCGI protocol) -> Django (via WSGI protocol)
</code></pre>
<p>Django has several "django.core.handlers" for the various interfaces.</p>
<p>For mod_fastcgi, Django provides a <code>manage.py runfcgi</code> that integrates FLUP and the handler.</p>
<p>For mod_wsgi, there's a core handler for this.</p>
<p><strong>How to install WSGI support ?</strong></p>
<p>Follow these instructions.</p>
<p><a href="http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango">http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango</a></p>
<p>For background see this</p>
<p><a href="http://docs.djangoproject.com/en/dev/howto/deployment/#howto-deployment-index">http://docs.djangoproject.com/en/dev/howto/deployment/#howto-deployment-index</a></p>
| 200 | 2009-02-06T13:04:12Z | [
"python",
"apache",
"cgi",
"wsgi"
] |
How Python web frameworks, WSGI and CGI fit together | 219,110 | <p>I have a <a href="http://en.wikipedia.org/wiki/Bluehost">Bluehost</a> account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in <code>.htaccess</code>:</p>
<pre><code>Options +ExecCGI
AddType text/html py
AddHandler cgi-script .py
</code></pre>
<p>Now, whenever I look up web programming with Python, I hear a lot about WSGI and how most frameworks use it. But I just don't understand how it all fits together, especially when my web server is given (Apache running at a host's machine) and not something I can really play with (except defining <code>.htaccess</code> commands).</p>
<p>How are <a href="http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface">WSGI</a>, CGI, and the frameworks all connected? What do I need to know, install, and do if I want to run a web framework (say <a href="http://webpy.org/">web.py</a> or <a href="http://en.wikipedia.org/wiki/CherryPy">CherryPy</a>) on my basic CGI configuration? How to install WSGI support?</p>
| 127 | 2008-10-20T16:43:57Z | 9,932,664 | <p>If you are unclear on all the terms in this space, and lets face it, its a confusing acronym-laden one, there's also a good background reader in the form of an official python HOWTO which discusses CGI vs. FastCGI vs. WSGI and so on: <a href="http://docs.python.org/howto/webservers.html">http://docs.python.org/howto/webservers.html</a></p>
| 6 | 2012-03-29T20:04:51Z | [
"python",
"apache",
"cgi",
"wsgi"
] |
How do I use Tkinter with Python on Windows Vista? | 219,215 | <p>I installed Python 2.6 for one user on Windows Vista. Python works okay, but when I try: <code>import Tkinter</code>, it says the side-by-side configuration has errors. I've tried tinkering with the Visual Studio runtime, with no good results. Any ideas on how to resolve this?</p>
| 3 | 2008-10-20T17:19:57Z | 219,284 | <p>Maybe you should downgrade to 2.5 version?</p>
| 1 | 2008-10-20T17:45:02Z | [
"python",
"windows",
"windows-vista",
"tkinter"
] |
How do I use Tkinter with Python on Windows Vista? | 219,215 | <p>I installed Python 2.6 for one user on Windows Vista. Python works okay, but when I try: <code>import Tkinter</code>, it says the side-by-side configuration has errors. I've tried tinkering with the Visual Studio runtime, with no good results. Any ideas on how to resolve this?</p>
| 3 | 2008-10-20T17:19:57Z | 219,326 | <p>It seems this is a one of the many weird Vista problems and some random reinstalling, installing/upgrading of the visual studio runtime or some such seems sometimes to help, or disabling sxs in the system configuration or writing a manifest file etc.</p>
<p>Though I think you should downgrade to windows XP.</p>
| 1 | 2008-10-20T18:03:30Z | [
"python",
"windows",
"windows-vista",
"tkinter"
] |
How do I use Tkinter with Python on Windows Vista? | 219,215 | <p>I installed Python 2.6 for one user on Windows Vista. Python works okay, but when I try: <code>import Tkinter</code>, it says the side-by-side configuration has errors. I've tried tinkering with the Visual Studio runtime, with no good results. Any ideas on how to resolve this?</p>
| 3 | 2008-10-20T17:19:57Z | 792,527 | <p>python 2.6.2 + tkinter 8.5, no problems</p>
| -1 | 2009-04-27T07:34:14Z | [
"python",
"windows",
"windows-vista",
"tkinter"
] |
django,fastcgi: how to manage a long running process? | 219,329 | <p>I have inherited a django+fastcgi application which needs to be modified to perform a lengthy computation (up to half an hour or more). What I want to do is run the computation in the background and return a "your job has been started" -type response. While the process is running, further hits to the url should return "your job is still running" until the job finishes at which point the results of the job should be returned. Any subsequent hit on the url should return the cached result. </p>
<p>I'm an utter novice at django and haven't done any significant web work in a decade so I don't know if there's a built-in way to do what I want. I've tried starting the process via subprocess.Popen(), and that works fine except for the fact it leaves a defunct entry in the process table. I need a clean solution that can remove temporary files and any traces of the process once it has finished.</p>
<p>I've also experimented with fork() and threads and have yet to come up with a viable solution. Is there a canonical solution to what seems to me to be a pretty common use case? FWIW this will only be used on an internal server with very low traffic.</p>
| 8 | 2008-10-20T18:05:22Z | 219,353 | <p>Maybe you could look at the problem the other way around.</p>
<p>Maybe you could try <a href="http://code.google.com/p/django-queue-service/" rel="nofollow">DjangoQueueService</a>, and have a "daemon" listening to the queue, seeing if there's something new and process it.</p>
| 3 | 2008-10-20T18:13:38Z | [
"python",
"django",
"fastcgi"
] |
django,fastcgi: how to manage a long running process? | 219,329 | <p>I have inherited a django+fastcgi application which needs to be modified to perform a lengthy computation (up to half an hour or more). What I want to do is run the computation in the background and return a "your job has been started" -type response. While the process is running, further hits to the url should return "your job is still running" until the job finishes at which point the results of the job should be returned. Any subsequent hit on the url should return the cached result. </p>
<p>I'm an utter novice at django and haven't done any significant web work in a decade so I don't know if there's a built-in way to do what I want. I've tried starting the process via subprocess.Popen(), and that works fine except for the fact it leaves a defunct entry in the process table. I need a clean solution that can remove temporary files and any traces of the process once it has finished.</p>
<p>I've also experimented with fork() and threads and have yet to come up with a viable solution. Is there a canonical solution to what seems to me to be a pretty common use case? FWIW this will only be used on an internal server with very low traffic.</p>
| 8 | 2008-10-20T18:05:22Z | 397,968 | <p>I have to solve a similar problem now. It is not going to be a public site, but similarly, an internal server with low traffic.</p>
<p>Technical constraints:</p>
<ul>
<li>all input data to the long running process can be supplied on its start</li>
<li>long running process does not require user interaction (except for the initial input to start a process)</li>
<li>the time of the computation is long enough so that the results cannot be served to the client in an immediate HTTP response</li>
<li>some sort of feedback (sort of progress bar) from the long running process is required.</li>
</ul>
<p>Hence, we need at least two web âviewsâ: one to initiate the long running process, and the other, to monitor its status/collect the results.</p>
<p>We also need some sort of interprocess communication: send user data from the <em>initiator</em> (the web server on http request) to the <em>long running process</em>, and then send its results to the <em>reciever</em> (again web server, driven by http requests). The former is easy, the latter is less obvious. Unlike in normal unix programming, the receiver is not known initially. The receiver may be a different process from the initiator, and it may start when the long running job is still in progress or is already finished. So the pipes do not work and we need some permamence of the results of the long running process.</p>
<p>I see two possible solutions:</p>
<ul>
<li>dispatch launches of the long running processes to the long running job manager (this is probably what the above-mentioned django-queue-service is);</li>
<li>save the results permanently, either in a file or in DB.</li>
</ul>
<p>I preferred to use temporary files and to remember their locaiton in the session data. I don't think it can be made more simple.</p>
<p>A job script (this is the long running process), <code>myjob.py</code>:</p>
<pre><code>import sys
from time import sleep
i = 0
while i < 1000:
print 'myjob:', i
i=i+1
sleep(0.1)
sys.stdout.flush()
</code></pre>
<p>django <code>urls.py</code> mapping:</p>
<pre><code>urlpatterns = patterns('',
(r'^startjob/$', 'mysite.myapp.views.startjob'),
(r'^showjob/$', 'mysite.myapp.views.showjob'),
(r'^rmjob/$', 'mysite.myapp.views.rmjob'),
)
</code></pre>
<p>django views:</p>
<pre><code>from tempfile import mkstemp
from os import fdopen,unlink,kill
from subprocess import Popen
import signal
def startjob(request):
"""Start a new long running process unless already started."""
if not request.session.has_key('job'):
# create a temporary file to save the resuls
outfd,outname=mkstemp()
request.session['jobfile']=outname
outfile=fdopen(outfd,'a+')
proc=Popen("python myjob.py",shell=True,stdout=outfile)
# remember pid to terminate the job later
request.session['job']=proc.pid
return HttpResponse('A <a href="/showjob/">new job</a> has started.')
def showjob(request):
"""Show the last result of the running job."""
if not request.session.has_key('job'):
return HttpResponse('Not running a job.'+\
'<a href="/startjob/">Start a new one?</a>')
else:
filename=request.session['jobfile']
results=open(filename)
lines=results.readlines()
try:
return HttpResponse(lines[-1]+\
'<p><a href="/rmjob/">Terminate?</a>')
except:
return HttpResponse('No results yet.'+\
'<p><a href="/rmjob/">Terminate?</a>')
return response
def rmjob(request):
"""Terminate the runining job."""
if request.session.has_key('job'):
job=request.session['job']
filename=request.session['jobfile']
try:
kill(job,signal.SIGKILL) # unix only
unlink(filename)
except OSError, e:
pass # probably the job has finished already
del request.session['job']
del request.session['jobfile']
return HttpResponseRedirect('/startjob/') # start a new one
</code></pre>
| 4 | 2008-12-29T15:51:23Z | [
"python",
"django",
"fastcgi"
] |
Iâm stunned: weird problem with python and sockets + threads | 219,547 | <p>I have a python script that is a http-server: <a href="http://paste2.org/p/89701" rel="nofollow">http://paste2.org/p/89701</a>, when benchmarking it against ApacheBench (ab) with a concurrency level (-c switch) that is lower then or equal to the value i specified in the socket.listen()-call in the sourcecode everything works fine, but as soon as put the concurrency level in apache bench above the value in the socket.listen()-call performance drops through the floor, some example:</p>
<ul>
<li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>10</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>1200req/s</strong></li>
<li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>11</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>40req/s</strong></li>
<li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>100</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>1000req/s</strong></li>
<li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>101</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>32req/s</strong></li>
</ul>
<p>Nothing changes in the code between the two calls, I canât figure out what is wrong - been at this problem for one day now. Also note that: The multiplexing version of the same code (I wrote to compare to the threaded version) works FINE no matter what socket.listen() is set to or what the concurrency (-c switch) in apache is set to.</p>
<p><em>I've spent a day on IRC/python docs, posted on comp.lang.python and on my blog - I can't find ANYONE that even has an idea what could be wrong. Help me!</em></p>
| 2 | 2008-10-20T19:19:45Z | 219,642 | <p>I found <a href="http://www.mail-archive.com/[email protected]/msg22589.html" rel="nofollow">this article</a> on backlog on tomcat / java which gives an interesting insight in the backlog:</p>
<blockquote>
<p>for example, if all threads are busy
in java handling requests, the kernel
will handle SYN and TCP handshakes
until its backlog is full. when the
backlog is full, it will simply drop
future SYN requests. it will not send
a RST, ie causing "Connection refused"
on the client, instead the client will
assume the package was lost and
retransmit the SYN. hopefully, the
backlog queue will have cleared up by
then.</p>
</blockquote>
<p>As I interpret it, by asking ab to create more simultaneous connection than your
socket is configured to handle packets get dropped, not refused, and I do not know
how ab handles that. It may be that it retransmits the SYN, but possibly after waiting
a while. This may even be specced somewhere (TCP protocol?).</p>
<p>As said, I do not know but I hope this hints at the cause. </p>
<p>Good luck!</p>
| 0 | 2008-10-20T19:48:00Z | [
"python",
"multithreading",
"apache",
"sockets"
] |
Iâm stunned: weird problem with python and sockets + threads | 219,547 | <p>I have a python script that is a http-server: <a href="http://paste2.org/p/89701" rel="nofollow">http://paste2.org/p/89701</a>, when benchmarking it against ApacheBench (ab) with a concurrency level (-c switch) that is lower then or equal to the value i specified in the socket.listen()-call in the sourcecode everything works fine, but as soon as put the concurrency level in apache bench above the value in the socket.listen()-call performance drops through the floor, some example:</p>
<ul>
<li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>10</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>1200req/s</strong></li>
<li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>11</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>40req/s</strong></li>
<li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>100</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>1000req/s</strong></li>
<li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>101</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>32req/s</strong></li>
</ul>
<p>Nothing changes in the code between the two calls, I canât figure out what is wrong - been at this problem for one day now. Also note that: The multiplexing version of the same code (I wrote to compare to the threaded version) works FINE no matter what socket.listen() is set to or what the concurrency (-c switch) in apache is set to.</p>
<p><em>I've spent a day on IRC/python docs, posted on comp.lang.python and on my blog - I can't find ANYONE that even has an idea what could be wrong. Help me!</em></p>
| 2 | 2008-10-20T19:19:45Z | 219,671 | <p>I cannot confirm your results, and your server is coded fishy. I whipped up my own server and do not have this problem either. Let's move the discussion to a simpler level:</p>
<pre><code>import thread, socket, Queue
connections = Queue.Queue()
num_threads = 10
backlog = 10
def request():
while 1:
conn = connections.get()
data = ''
while '\r\n\r\n' not in data:
data += conn.recv(4048)
conn.sendall('HTTP/1.1 200 OK\r\n\r\nHello World')
conn.close()
if __name__ == '__main__':
for _ in range(num_threads):
thread.start_new_thread(request, ())
acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
acceptor.bind(('', 1234))
acceptor.listen(backlog)
while 1:
conn, addr = acceptor.accept()
connections.put(conn)
</code></pre>
<p>which on my machine does:</p>
<pre><code>ab -n 10000 -c 10 http://127.0.0.1:1234/ --> 8695.03 [#/sec]
ab -n 10000 -c 11 http://127.0.0.1:1234/ --> 8529.41 [#/sec]
</code></pre>
| 7 | 2008-10-20T19:56:00Z | [
"python",
"multithreading",
"apache",
"sockets"
] |
Iâm stunned: weird problem with python and sockets + threads | 219,547 | <p>I have a python script that is a http-server: <a href="http://paste2.org/p/89701" rel="nofollow">http://paste2.org/p/89701</a>, when benchmarking it against ApacheBench (ab) with a concurrency level (-c switch) that is lower then or equal to the value i specified in the socket.listen()-call in the sourcecode everything works fine, but as soon as put the concurrency level in apache bench above the value in the socket.listen()-call performance drops through the floor, some example:</p>
<ul>
<li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>10</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>1200req/s</strong></li>
<li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>11</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>40req/s</strong></li>
<li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>100</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>1000req/s</strong></li>
<li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>101</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>32req/s</strong></li>
</ul>
<p>Nothing changes in the code between the two calls, I canât figure out what is wrong - been at this problem for one day now. Also note that: The multiplexing version of the same code (I wrote to compare to the threaded version) works FINE no matter what socket.listen() is set to or what the concurrency (-c switch) in apache is set to.</p>
<p><em>I've spent a day on IRC/python docs, posted on comp.lang.python and on my blog - I can't find ANYONE that even has an idea what could be wrong. Help me!</em></p>
| 2 | 2008-10-20T19:19:45Z | 219,676 | <p>it looks like you're not really getting concurrency. apparently, when you do socket.accept(), the main thread doesn't go immediately back to waiting for the next connection. maybe your connection-handling thread is only python code, so you're getting sequentialized by the SIL (single interpreder lock).</p>
<p>if there's not heavy communications between threads, better use a multi-process scheme (with a pool of pre-spawned processes, of course)</p>
| 0 | 2008-10-20T19:57:04Z | [
"python",
"multithreading",
"apache",
"sockets"
] |
Iâm stunned: weird problem with python and sockets + threads | 219,547 | <p>I have a python script that is a http-server: <a href="http://paste2.org/p/89701" rel="nofollow">http://paste2.org/p/89701</a>, when benchmarking it against ApacheBench (ab) with a concurrency level (-c switch) that is lower then or equal to the value i specified in the socket.listen()-call in the sourcecode everything works fine, but as soon as put the concurrency level in apache bench above the value in the socket.listen()-call performance drops through the floor, some example:</p>
<ul>
<li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>10</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>1200req/s</strong></li>
<li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>11</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>40req/s</strong></li>
<li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>100</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>1000req/s</strong></li>
<li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>101</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>32req/s</strong></li>
</ul>
<p>Nothing changes in the code between the two calls, I canât figure out what is wrong - been at this problem for one day now. Also note that: The multiplexing version of the same code (I wrote to compare to the threaded version) works FINE no matter what socket.listen() is set to or what the concurrency (-c switch) in apache is set to.</p>
<p><em>I've spent a day on IRC/python docs, posted on comp.lang.python and on my blog - I can't find ANYONE that even has an idea what could be wrong. Help me!</em></p>
| 2 | 2008-10-20T19:19:45Z | 219,824 | <p>For the heck of it I also implemented an asynchronous version:</p>
<pre><code>import socket, Queue, select
class Request(object):
def __init__(self, conn):
self.conn = conn
self.fileno = conn.fileno
self.perform = self._perform().next
def _perform(self):
data = self.conn.recv(4048)
while '\r\n\r\n' not in data:
msg = self.conn.recv(4048)
if msg:
data += msg
yield
else:
break
reading.remove(self)
writing.append(self)
data = 'HTTP/1.1 200 OK\r\n\r\nHello World'
while data:
sent = self.conn.send(data)
data = data[sent:]
yield
writing.remove(self)
self.conn.close()
class Acceptor:
def __init__(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', 1234))
sock.listen(10)
self.sock = sock
self.fileno = sock.fileno
def perform(self):
conn, addr = self.sock.accept()
reading.append(Request(conn))
if __name__ == '__main__':
reading = [Acceptor()]
writing = list()
while 1:
readable, writable, error = select.select(reading, writing, [])
for action in readable + writable:
try: action.perform()
except StopIteration: pass
</code></pre>
<p>which performs:</p>
<pre><code>ab -n 10000 -c 10 http://127.0.0.1:1234/ --> 16822.13 [#/sec]
ab -n 10000 -c 11 http://127.0.0.1:1234/ --> 15704.41 [#/sec]
</code></pre>
| 4 | 2008-10-20T20:37:12Z | [
"python",
"multithreading",
"apache",
"sockets"
] |
Iâm stunned: weird problem with python and sockets + threads | 219,547 | <p>I have a python script that is a http-server: <a href="http://paste2.org/p/89701" rel="nofollow">http://paste2.org/p/89701</a>, when benchmarking it against ApacheBench (ab) with a concurrency level (-c switch) that is lower then or equal to the value i specified in the socket.listen()-call in the sourcecode everything works fine, but as soon as put the concurrency level in apache bench above the value in the socket.listen()-call performance drops through the floor, some example:</p>
<ul>
<li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>10</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>1200req/s</strong></li>
<li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>11</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>40req/s</strong></li>
<li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>100</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>1000req/s</strong></li>
<li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>101</strong> <a href="http://localhost/" rel="nofollow">http://localhost/</a> = <strong>32req/s</strong></li>
</ul>
<p>Nothing changes in the code between the two calls, I canât figure out what is wrong - been at this problem for one day now. Also note that: The multiplexing version of the same code (I wrote to compare to the threaded version) works FINE no matter what socket.listen() is set to or what the concurrency (-c switch) in apache is set to.</p>
<p><em>I've spent a day on IRC/python docs, posted on comp.lang.python and on my blog - I can't find ANYONE that even has an idea what could be wrong. Help me!</em></p>
| 2 | 2008-10-20T19:19:45Z | 222,713 | <p>Ok, so I ran the code on a totally different server - (a vps I got at slicehost), not a single problem (everything works as expected) so honestly I think it's something wrong with my laptop now ;p </p>
<p>Thanks for everyones help though!</p>
| 0 | 2008-10-21T17:21:36Z | [
"python",
"multithreading",
"apache",
"sockets"
] |
Ensure a single instance of an application in Linux | 220,525 | <p>I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and check that at startup. Unfortunately, I don't know of any facilities in Linux that can do this. </p>
<p>I'm looking for something that will automatically be released should the application crash unexpectedly. I don't want to have to burden my users with having to manually delete lock files because I crashed.</p>
| 28 | 2008-10-21T01:58:30Z | 220,536 | <p>If you create a lock file and put the pid in it, you can check your process id against it and tell if you crashed, no?</p>
<p>I haven't done this personally, so take with appropriate amounts of salt. :p</p>
| 0 | 2008-10-21T02:08:17Z | [
"python",
"linux",
"singleinstance"
] |
Ensure a single instance of an application in Linux | 220,525 | <p>I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and check that at startup. Unfortunately, I don't know of any facilities in Linux that can do this. </p>
<p>I'm looking for something that will automatically be released should the application crash unexpectedly. I don't want to have to burden my users with having to manually delete lock files because I crashed.</p>
| 28 | 2008-10-21T01:58:30Z | 220,539 | <p>Can you use the 'pidof' utility? If your app is running, pidof will write the Process ID of your app to stdout. If not, it will print a newline (LF) and return an error code.</p>
<p>Example (from bash, for simplicity):</p>
<pre><code>linux# pidof myapp
8947
linux# pidof nonexistent_app
linux#
</code></pre>
| 0 | 2008-10-21T02:09:29Z | [
"python",
"linux",
"singleinstance"
] |
Ensure a single instance of an application in Linux | 220,525 | <p>I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and check that at startup. Unfortunately, I don't know of any facilities in Linux that can do this. </p>
<p>I'm looking for something that will automatically be released should the application crash unexpectedly. I don't want to have to burden my users with having to manually delete lock files because I crashed.</p>
| 28 | 2008-10-21T01:58:30Z | 220,541 | <p>By far the most common method is to drop a file into /var/run/ called [application].pid which contains only the PID of the running process, or parent process.
As an alternative, you can create a named pipe in the same directory to be able to send messages to the active process, e.g. to open a new file.</p>
| 0 | 2008-10-21T02:10:09Z | [
"python",
"linux",
"singleinstance"
] |
Ensure a single instance of an application in Linux | 220,525 | <p>I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and check that at startup. Unfortunately, I don't know of any facilities in Linux that can do this. </p>
<p>I'm looking for something that will automatically be released should the application crash unexpectedly. I don't want to have to burden my users with having to manually delete lock files because I crashed.</p>
| 28 | 2008-10-21T01:58:30Z | 220,542 | <p>There are several common techniques including using semaphores. The one I see used most often is to create a "pid lock file" on startup that contains the pid of the running process. If the file already exists when the program starts up, open it up and grab the pid inside, check to see if a process with that pid is running, if it is check the cmdline value in /proc/<em>pid</em> to see if it is an instance of your program, if it is then quit, otherwise overwrite the file with your pid. The usual name for the pid file is *application_name*<code>.pid</code>.</p>
| 21 | 2008-10-21T02:10:24Z | [
"python",
"linux",
"singleinstance"
] |
Ensure a single instance of an application in Linux | 220,525 | <p>I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and check that at startup. Unfortunately, I don't know of any facilities in Linux that can do this. </p>
<p>I'm looking for something that will automatically be released should the application crash unexpectedly. I don't want to have to burden my users with having to manually delete lock files because I crashed.</p>
| 28 | 2008-10-21T01:58:30Z | 220,544 | <p><a href="http://www.opengroup.org/onlinepubs/007908799/xsh/semaphore.h.html" rel="nofollow">The set of functions defined in <code>semaphore.h</code></a> -- <code>sem_open()</code>, <code>sem_trywait()</code>, etc -- are the POSIX equivalent, I believe.</p>
| 1 | 2008-10-21T02:10:53Z | [
"python",
"linux",
"singleinstance"
] |
Ensure a single instance of an application in Linux | 220,525 | <p>I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and check that at startup. Unfortunately, I don't know of any facilities in Linux that can do this. </p>
<p>I'm looking for something that will automatically be released should the application crash unexpectedly. I don't want to have to burden my users with having to manually delete lock files because I crashed.</p>
| 28 | 2008-10-21T01:58:30Z | 220,590 | <p>Look for a python module that interfaces to SYSV semaphores on unix. The semaphores have a SEM_UNDO flag which will cause the resources held by the a process to be released if the process crashes.</p>
<p>Otherwise as Bernard suggested, you can use </p>
<pre><code>import os
os.getpid()
</code></pre>
<p>And write it to /var/run/*application_name*.pid. When the process starts, it should check if the pid in /var/run/*application_name*.pid is listed in the ps table and quit if it is, otherwise write its own pid into /var/run/*application_name*.pid. In the following var_run_pid is the pid you read from /var/run/*application_name*.pid</p>
<pre><code>cmd = "ps -p %s -o comm=" % var_run_pid
app_name = os.popen(cmd).read().strip()
if len(app_name) > 0:
Already running
</code></pre>
| 1 | 2008-10-21T02:39:56Z | [
"python",
"linux",
"singleinstance"
] |
Ensure a single instance of an application in Linux | 220,525 | <p>I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and check that at startup. Unfortunately, I don't know of any facilities in Linux that can do this. </p>
<p>I'm looking for something that will automatically be released should the application crash unexpectedly. I don't want to have to burden my users with having to manually delete lock files because I crashed.</p>
| 28 | 2008-10-21T01:58:30Z | 220,709 | <p>The Right Thing is advisory locking using <code>flock(LOCK_EX)</code>; in Python, this is found in the <A HREF="http://docs.python.org/3/library/fcntl.html"><code>fcntl</code> module</A>.</p>
<p>Unlike pidfiles, these locks are always automatically released when your process dies for any reason, have no race conditions exist relating to file deletion (as the file doesn't <I>need</I> to be deleted to release the lock), and there's no chance of a different process inheriting the PID and thus appearing to validate a stale lock.</p>
<p>If you want unclean shutdown detection, you can write a marker (such as your PID, for traditionalists) into the file after grabbing the lock, and then truncate the file to 0-byte status before a clean shutdown (while the lock is being held); thus, if the lock is not held and the file is non-empty, an unclean shutdown is indicated.</p>
| 49 | 2008-10-21T03:43:36Z | [
"python",
"linux",
"singleinstance"
] |
Ensure a single instance of an application in Linux | 220,525 | <p>I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and check that at startup. Unfortunately, I don't know of any facilities in Linux that can do this. </p>
<p>I'm looking for something that will automatically be released should the application crash unexpectedly. I don't want to have to burden my users with having to manually delete lock files because I crashed.</p>
| 28 | 2008-10-21T01:58:30Z | 221,159 | <p>Complete locking solution using the <code>fcntl</code> module:</p>
<pre><code>import fcntl
pid_file = 'program.pid'
fp = open(pid_file, 'w')
try:
fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
# another instance is running
sys.exit(1)
</code></pre>
| 20 | 2008-10-21T08:30:11Z | [
"python",
"linux",
"singleinstance"
] |
Ensure a single instance of an application in Linux | 220,525 | <p>I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and check that at startup. Unfortunately, I don't know of any facilities in Linux that can do this. </p>
<p>I'm looking for something that will automatically be released should the application crash unexpectedly. I don't want to have to burden my users with having to manually delete lock files because I crashed.</p>
| 28 | 2008-10-21T01:58:30Z | 476,133 | <p>wxWidgets offers a wxSingleInstanceChecker class for this purpose: <a href="http://www.wxpython.org/docs/api/wx.SingleInstanceChecker-class.html">wxPython doc</a>, or <a href="http://docs.wxwidgets.org/stable/wx_wxsingleinstancechecker.html">wxWidgets doc</a>. The wxWidgets doc has sample code in C++, but the python equivalent should be something like this (untested):</p>
<pre><code> name = "MyApp-%s" % wx.GetUserId()
checker = wx.SingleInstanceChecker(name)
if checker.IsAnotherRunning():
return False
</code></pre>
| 8 | 2009-01-24T15:20:51Z | [
"python",
"linux",
"singleinstance"
] |
Ensure a single instance of an application in Linux | 220,525 | <p>I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and check that at startup. Unfortunately, I don't know of any facilities in Linux that can do this. </p>
<p>I'm looking for something that will automatically be released should the application crash unexpectedly. I don't want to have to burden my users with having to manually delete lock files because I crashed.</p>
| 28 | 2008-10-21T01:58:30Z | 559,978 | <p>I've made a basic framework for running these kinds of applications when you want to be able to pass the command line arguments of subsequent attempted instances to the first one. An instance will start listening on a predefined port if it does not find an instance already listening there. If an instance already exists, it sends its command line arguments over the socket and exits.</p>
<p><a href="http://dwiel.net/blog/single-instance-application-with-command-line-interface/" rel="nofollow">code w/ explanation</a></p>
| 0 | 2009-02-18T05:41:36Z | [
"python",
"linux",
"singleinstance"
] |
Ensure a single instance of an application in Linux | 220,525 | <p>I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and check that at startup. Unfortunately, I don't know of any facilities in Linux that can do this. </p>
<p>I'm looking for something that will automatically be released should the application crash unexpectedly. I don't want to have to burden my users with having to manually delete lock files because I crashed.</p>
| 28 | 2008-10-21T01:58:30Z | 15,016,759 | <p>This builds upon the <a href="https://stackoverflow.com/a/221159/832230">answer</a> by user <a href="https://stackoverflow.com/users/12138/zgoda">zgoda</a>. It mainly addresses a tricky concern having to do with write access to the lock file. In particular, if the lock file was first created by <code>root</code>, another user <code>foo</code> can then no successfully longer attempt to rewrite this file due to an absence of write permissions for user <code>foo</code>. The obvious solution seems to be to create the file with write permissions for everyone. This solution also builds upon a different <a href="https://stackoverflow.com/a/15015748/832230">answer</a> by me, having to do creating a file with such custom permissions. This concern is important in the real world where your program may be run by any user including <code>root</code>.</p>
<pre><code>import fcntl, os, stat, tempfile
app_name = 'myapp' # <-- Customize this value
# Establish lock file settings
lf_name = '.{}.lock'.format(app_name)
lf_path = os.path.join(tempfile.gettempdir(), lf_name)
lf_flags = os.O_WRONLY | os.O_CREAT
lf_mode = stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH # This is 0o222, i.e. 146
# Create lock file
# Regarding umask, see https://stackoverflow.com/a/15015748/832230
umask_original = os.umask(0)
try:
lf_fd = os.open(lf_path, lf_flags, lf_mode)
finally:
os.umask(umask_original)
# Try locking the file
try:
fcntl.lockf(lf_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
msg = ('Error: {} may already be running. Only one instance of it '
'can run at a time.'
).format('appname')
exit(msg)
</code></pre>
<p>A limitation of the above code is that if the lock file already existed with unexpected permissions, those permissions will not be corrected.</p>
<p>I would've liked to use <code>/var/run/<appname>/</code> as the directory for the lock file, but creating this directory requires <code>root</code> permissions. You can make your own decision for which directory to use.</p>
<p>Note that there is no need to open a file handle to the lock file.</p>
| 6 | 2013-02-22T04:18:27Z | [
"python",
"linux",
"singleinstance"
] |
Ensure a single instance of an application in Linux | 220,525 | <p>I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and check that at startup. Unfortunately, I don't know of any facilities in Linux that can do this. </p>
<p>I'm looking for something that will automatically be released should the application crash unexpectedly. I don't want to have to burden my users with having to manually delete lock files because I crashed.</p>
| 28 | 2008-10-21T01:58:30Z | 34,659,754 | <p>Here's the TCP port-based solution:</p>
<pre><code># Use a listening socket as a mutex against multiple invocations
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 5080))
s.listen(1)
</code></pre>
| 1 | 2016-01-07T16:04:31Z | [
"python",
"linux",
"singleinstance"
] |
Including PYDs/DLLs in py2exe builds | 220,777 | <p>One of the modules for my app uses functions from a .pyd file. There's an option to exclude dlls (exclude_dlls) but is there one for including them? The build process doesn't seem to be copying the .pyd in my module despite copying the rest of the files (.py). I also need to include a .dll. How do I get py2exe to include both .pyd and .dll files?</p>
| 9 | 2008-10-21T04:40:57Z | 220,830 | <p>If they're not being automatically detected, try manually copying them into py2exe's temporary build directory. They will be included in the final executable.</p>
| 1 | 2008-10-21T05:08:35Z | [
"python",
"dll",
"installation",
"py2exe",
"pyd"
] |
Including PYDs/DLLs in py2exe builds | 220,777 | <p>One of the modules for my app uses functions from a .pyd file. There's an option to exclude dlls (exclude_dlls) but is there one for including them? The build process doesn't seem to be copying the .pyd in my module despite copying the rest of the files (.py). I also need to include a .dll. How do I get py2exe to include both .pyd and .dll files?</p>
| 9 | 2008-10-21T04:40:57Z | 220,892 | <p>You can modify the setup script to copy the files explicitly:</p>
<pre><code>script = "PyInvaders.py" #name of starting .PY
project_name = os.path.splitext(os.path.split(script)[1])[0]
setup(name=project_name, scripts=[script]) #this installs the program
#also need to hand copy the extra files here
def installfile(name):
dst = os.path.join('dist', project_name)
print 'copying', name, '->', dst
if os.path.isdir(name):
dst = os.path.join(dst, name)
if os.path.isdir(dst):
shutil.rmtree(dst)
shutil.copytree(name, dst)
elif os.path.isfile(name):
shutil.copy(name, dst)
else:
print 'Warning, %s not found' % name
pygamedir = os.path.split(pygame.base.__file__)[0]
installfile(os.path.join(pygamedir, pygame.font.get_default_font()))
installfile(os.path.join(pygamedir, 'pygame_icon.bmp'))
for data in extra_data:
installfile(data)
</code></pre>
<p>etc... modify to suit your needs, of course.</p>
| 2 | 2008-10-21T05:51:12Z | [
"python",
"dll",
"installation",
"py2exe",
"pyd"
] |
Including PYDs/DLLs in py2exe builds | 220,777 | <p>One of the modules for my app uses functions from a .pyd file. There's an option to exclude dlls (exclude_dlls) but is there one for including them? The build process doesn't seem to be copying the .pyd in my module despite copying the rest of the files (.py). I also need to include a .dll. How do I get py2exe to include both .pyd and .dll files?</p>
| 9 | 2008-10-21T04:40:57Z | 224,154 | <p>Maybe you could use the data_files option to setup():</p>
<pre><code>import glob
setup(name='MyApp',
# other options,
data_files=[('.', glob.glob('*.dll')),
('.', glob.glob('*.pyd'))],
)
</code></pre>
<p>data_files should be a list of tuples, where each tuple contains:</p>
<ol>
<li>The target directory.</li>
<li>A list of files to copy.</li>
</ol>
<p>This won't put the files into library.zip, which shouldn't be a problem for dlls, but I don't know about pyd files.</p>
| 2 | 2008-10-22T01:22:00Z | [
"python",
"dll",
"installation",
"py2exe",
"pyd"
] |
Including PYDs/DLLs in py2exe builds | 220,777 | <p>One of the modules for my app uses functions from a .pyd file. There's an option to exclude dlls (exclude_dlls) but is there one for including them? The build process doesn't seem to be copying the .pyd in my module despite copying the rest of the files (.py). I also need to include a .dll. How do I get py2exe to include both .pyd and .dll files?</p>
| 9 | 2008-10-21T04:40:57Z | 224,274 | <p>.pyd's and .DLL's are different here, in that a .pyd ought to be automatically found by modulefinder and so included (as long as you have the appropriate "import" statement) without needing to do anything. If one is missed, you do the same thing as if a .py file was missed (they're both just modules): use the "include" option for the py2exe options.</p>
<p>Modulefinder will not necessarily find dependencies on .DLLs (py2exe can detect some), so you may need to explicitly include these, with the 'data_files' option.</p>
<p>For example, where you had two .DLL's ('foo.dll' and 'bar.dll') to include, and three .pyd's ('module1.pyd', 'module2.pyd', and 'module3.pyd') to include:</p>
<pre><code>setup(name='App',
# other options,
data_files=[('.', 'foo.dll'), ('.', 'bar.dll')],
options = {"py2exe" : {"includes" : "module1,module2,module3"}}
)
</code></pre>
| 11 | 2008-10-22T02:27:44Z | [
"python",
"dll",
"installation",
"py2exe",
"pyd"
] |
load dll from python | 220,902 | <p>I'm building a python application from some source code I've found <a href="http://code.google.com/p/enso" rel="nofollow">Here</a></p>
<p>I've managed to compile and fix some problems by searching the web, but I'm stuck at this point:</p>
<p>When running the application this message appears.</p>
<p><img src="http://img511.imageshack.us/img511/4481/loadfr0.png" alt="alt text" /></p>
<p>This python app, usues swig to link to c/c++ code.</p>
<p>I have VC++2005 express edition which I used to compile along with scons
and Python 2.5 ( and tried 2.4 too ) </p>
<p>The dlls that are attempting to load is "msvcr80.dll" because before the message was "msvcr80.dll" cannot be found or something like that, so I got it and drop it in window32 folder.</p>
<p>For what I've read in here:
<a href="http://msdn.microsoft.com/en-us/library/ms235591" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms235591</a>(VS.80).aspx</p>
<p>The solution is to run MT with the manifest and the dll file. I did it already and doesn't work either.</p>
<p>Could anyone point me to the correct direction?</p>
<p>This is the content of the manifest fie:</p>
<pre><code><?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<dependency>
<dependentAssembly>
<assemblyIdentity type='win32' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' />
</dependentAssembly>
</dependency>
</assembly>
</code></pre>
<p>I'm going to try Python 2.6 now, I'm not quite sure of understanding the problem, but Python 2.5 and Python 2.5 .exe had the string "MSVCR71.dll" inside the .exe file. But probably this has nothing to do.</p>
<p>ps. if only everything was as easy as jar files :( </p>
<p>This is the stack trace for completeness</p>
<pre><code>None
INFO:root:Skipping provider enso.platform.osx.
INFO:root:Skipping provider enso.platform.linux.
INFO:root:Added provider enso.platform.win32.
Traceback (most recent call last):
File "scripts\run_enso.py", line 24, in <module>
enso.run()
File "C:\oreyes\apps\enso\enso-read-only\enso\__init__.py", line 40, in run
from enso.events import EventManager
File "C:\oreyes\apps\enso\enso-read-only\enso\events.py", line 60, in <module>
from enso import input
File "C:\oreyes\apps\enso\enso-read-only\enso\input\__init__.py", line 3, in <module>
_input = enso.providers.getInterface( "input" )
File "C:\oreyes\apps\enso\enso-read-only\enso\providers.py", line 137, in getInterface
interface = provider.provideInterface( name )
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\__init__.py", line 48, in provideInterface
import enso.platform.win32.input
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\input\__init__.py", line 3, in <module>
from InputManager import *
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\input\InputManager.py", line 7, in <module>
import _InputManager
ImportError: DLL load failed: Error en una rutina de inicializaci¾n de biblioteca de vÃnculos dinÃmicos (DLL).
</code></pre>
| 2 | 2008-10-21T05:57:08Z | 220,955 | <p>You probably need to install the VC++ runtime redistributables. The links to them are <a href="http://stackoverflow.com/questions/99479/visual-cstudio-application-configuration-incorrect#100310">here</a>.</p>
| 0 | 2008-10-21T06:20:16Z | [
"python",
"swig",
"scons",
"dynamic-linking"
] |
load dll from python | 220,902 | <p>I'm building a python application from some source code I've found <a href="http://code.google.com/p/enso" rel="nofollow">Here</a></p>
<p>I've managed to compile and fix some problems by searching the web, but I'm stuck at this point:</p>
<p>When running the application this message appears.</p>
<p><img src="http://img511.imageshack.us/img511/4481/loadfr0.png" alt="alt text" /></p>
<p>This python app, usues swig to link to c/c++ code.</p>
<p>I have VC++2005 express edition which I used to compile along with scons
and Python 2.5 ( and tried 2.4 too ) </p>
<p>The dlls that are attempting to load is "msvcr80.dll" because before the message was "msvcr80.dll" cannot be found or something like that, so I got it and drop it in window32 folder.</p>
<p>For what I've read in here:
<a href="http://msdn.microsoft.com/en-us/library/ms235591" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms235591</a>(VS.80).aspx</p>
<p>The solution is to run MT with the manifest and the dll file. I did it already and doesn't work either.</p>
<p>Could anyone point me to the correct direction?</p>
<p>This is the content of the manifest fie:</p>
<pre><code><?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<dependency>
<dependentAssembly>
<assemblyIdentity type='win32' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' />
</dependentAssembly>
</dependency>
</assembly>
</code></pre>
<p>I'm going to try Python 2.6 now, I'm not quite sure of understanding the problem, but Python 2.5 and Python 2.5 .exe had the string "MSVCR71.dll" inside the .exe file. But probably this has nothing to do.</p>
<p>ps. if only everything was as easy as jar files :( </p>
<p>This is the stack trace for completeness</p>
<pre><code>None
INFO:root:Skipping provider enso.platform.osx.
INFO:root:Skipping provider enso.platform.linux.
INFO:root:Added provider enso.platform.win32.
Traceback (most recent call last):
File "scripts\run_enso.py", line 24, in <module>
enso.run()
File "C:\oreyes\apps\enso\enso-read-only\enso\__init__.py", line 40, in run
from enso.events import EventManager
File "C:\oreyes\apps\enso\enso-read-only\enso\events.py", line 60, in <module>
from enso import input
File "C:\oreyes\apps\enso\enso-read-only\enso\input\__init__.py", line 3, in <module>
_input = enso.providers.getInterface( "input" )
File "C:\oreyes\apps\enso\enso-read-only\enso\providers.py", line 137, in getInterface
interface = provider.provideInterface( name )
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\__init__.py", line 48, in provideInterface
import enso.platform.win32.input
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\input\__init__.py", line 3, in <module>
from InputManager import *
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\input\InputManager.py", line 7, in <module>
import _InputManager
ImportError: DLL load failed: Error en una rutina de inicializaci¾n de biblioteca de vÃnculos dinÃmicos (DLL).
</code></pre>
| 2 | 2008-10-21T05:57:08Z | 221,092 | <p>I've been able to compile and run Enso by using /LD as a compiler flag. This links dynamically to the MS Visual C++ runtime, and seems to allow you to get away without a manifest.</p>
<p>If you're using SCons, see the diff file here: <a href="http://paste2.org/p/69732" rel="nofollow">http://paste2.org/p/69732</a></p>
| 0 | 2008-10-21T07:53:11Z | [
"python",
"swig",
"scons",
"dynamic-linking"
] |
load dll from python | 220,902 | <p>I'm building a python application from some source code I've found <a href="http://code.google.com/p/enso" rel="nofollow">Here</a></p>
<p>I've managed to compile and fix some problems by searching the web, but I'm stuck at this point:</p>
<p>When running the application this message appears.</p>
<p><img src="http://img511.imageshack.us/img511/4481/loadfr0.png" alt="alt text" /></p>
<p>This python app, usues swig to link to c/c++ code.</p>
<p>I have VC++2005 express edition which I used to compile along with scons
and Python 2.5 ( and tried 2.4 too ) </p>
<p>The dlls that are attempting to load is "msvcr80.dll" because before the message was "msvcr80.dll" cannot be found or something like that, so I got it and drop it in window32 folder.</p>
<p>For what I've read in here:
<a href="http://msdn.microsoft.com/en-us/library/ms235591" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms235591</a>(VS.80).aspx</p>
<p>The solution is to run MT with the manifest and the dll file. I did it already and doesn't work either.</p>
<p>Could anyone point me to the correct direction?</p>
<p>This is the content of the manifest fie:</p>
<pre><code><?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<dependency>
<dependentAssembly>
<assemblyIdentity type='win32' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' />
</dependentAssembly>
</dependency>
</assembly>
</code></pre>
<p>I'm going to try Python 2.6 now, I'm not quite sure of understanding the problem, but Python 2.5 and Python 2.5 .exe had the string "MSVCR71.dll" inside the .exe file. But probably this has nothing to do.</p>
<p>ps. if only everything was as easy as jar files :( </p>
<p>This is the stack trace for completeness</p>
<pre><code>None
INFO:root:Skipping provider enso.platform.osx.
INFO:root:Skipping provider enso.platform.linux.
INFO:root:Added provider enso.platform.win32.
Traceback (most recent call last):
File "scripts\run_enso.py", line 24, in <module>
enso.run()
File "C:\oreyes\apps\enso\enso-read-only\enso\__init__.py", line 40, in run
from enso.events import EventManager
File "C:\oreyes\apps\enso\enso-read-only\enso\events.py", line 60, in <module>
from enso import input
File "C:\oreyes\apps\enso\enso-read-only\enso\input\__init__.py", line 3, in <module>
_input = enso.providers.getInterface( "input" )
File "C:\oreyes\apps\enso\enso-read-only\enso\providers.py", line 137, in getInterface
interface = provider.provideInterface( name )
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\__init__.py", line 48, in provideInterface
import enso.platform.win32.input
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\input\__init__.py", line 3, in <module>
from InputManager import *
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\input\InputManager.py", line 7, in <module>
import _InputManager
ImportError: DLL load failed: Error en una rutina de inicializaci¾n de biblioteca de vÃnculos dinÃmicos (DLL).
</code></pre>
| 2 | 2008-10-21T05:57:08Z | 221,200 | <p><strong>update</strong>
I've downloaded python2.6 and VS C++ express edition 2008 and the problem with the msvcr80.dll is gone ( I assume because Python and VSC++2008xe use msvscr90.dll) </p>
<p>I've compile with /LD and all the changes listed here: <a href="http://paste2.org/p/69732" rel="nofollow">http://paste2.org/p/69732</a> </p>
<p>And now the problem follows:</p>
<pre><code>INFO:root:Skipping provider enso.platform.osx.
INFO:root:Skipping provider enso.platform.linux.
INFO:root:Added provider enso.platform.win32.
INFO:root:Obtained interface 'input' from provider 'enso.platform.win32'.
Traceback (most recent call last):
File "scripts\run_enso.py", line 23, in <module>
enso.run()
File "C:\oreyes\apps\enso\enso-comunity\enso\__init__.py", line 41, in run
from enso.quasimode import Quasimode
File "C:\oreyes\apps\enso\enso-comunity\enso\quasimode\__init__.py", line 62, in <module>
from enso.quasimode.window import TheQuasimodeWindow
File "C:\oreyes\apps\enso\enso-comunity\enso\quasimode\window.py", line 65, in <module>
from enso.quasimode.linewindows import TextWindow
File "C:\oreyes\apps\enso\enso-comunity\enso\quasimode\linewindows.py", line 44, in <module>
from enso import cairo
File "C:\oreyes\apps\enso\enso-comunity\enso\cairo.py", line 3, in <module>
__cairoImpl = enso.providers.getInterface( "cairo" )
File "C:\oreyes\apps\enso\enso-comunity\enso\providers.py", line 137, in getInterface
interface = provider.provideInterface( name )
File "C:\oreyes\apps\enso\enso-comunity\enso\platform\win32\__init__.py", line 61, in provideInterface
import enso.platform.win32.cairo
File "C:\oreyes\apps\enso\enso-comunity\enso\platform\win32\cairo\__init__.py", line 1, in <module>
from _cairo import *
ImportError: No module named _cairo
</code></pre>
| 0 | 2008-10-21T08:50:26Z | [
"python",
"swig",
"scons",
"dynamic-linking"
] |
load dll from python | 220,902 | <p>I'm building a python application from some source code I've found <a href="http://code.google.com/p/enso" rel="nofollow">Here</a></p>
<p>I've managed to compile and fix some problems by searching the web, but I'm stuck at this point:</p>
<p>When running the application this message appears.</p>
<p><img src="http://img511.imageshack.us/img511/4481/loadfr0.png" alt="alt text" /></p>
<p>This python app, usues swig to link to c/c++ code.</p>
<p>I have VC++2005 express edition which I used to compile along with scons
and Python 2.5 ( and tried 2.4 too ) </p>
<p>The dlls that are attempting to load is "msvcr80.dll" because before the message was "msvcr80.dll" cannot be found or something like that, so I got it and drop it in window32 folder.</p>
<p>For what I've read in here:
<a href="http://msdn.microsoft.com/en-us/library/ms235591" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms235591</a>(VS.80).aspx</p>
<p>The solution is to run MT with the manifest and the dll file. I did it already and doesn't work either.</p>
<p>Could anyone point me to the correct direction?</p>
<p>This is the content of the manifest fie:</p>
<pre><code><?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<dependency>
<dependentAssembly>
<assemblyIdentity type='win32' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' />
</dependentAssembly>
</dependency>
</assembly>
</code></pre>
<p>I'm going to try Python 2.6 now, I'm not quite sure of understanding the problem, but Python 2.5 and Python 2.5 .exe had the string "MSVCR71.dll" inside the .exe file. But probably this has nothing to do.</p>
<p>ps. if only everything was as easy as jar files :( </p>
<p>This is the stack trace for completeness</p>
<pre><code>None
INFO:root:Skipping provider enso.platform.osx.
INFO:root:Skipping provider enso.platform.linux.
INFO:root:Added provider enso.platform.win32.
Traceback (most recent call last):
File "scripts\run_enso.py", line 24, in <module>
enso.run()
File "C:\oreyes\apps\enso\enso-read-only\enso\__init__.py", line 40, in run
from enso.events import EventManager
File "C:\oreyes\apps\enso\enso-read-only\enso\events.py", line 60, in <module>
from enso import input
File "C:\oreyes\apps\enso\enso-read-only\enso\input\__init__.py", line 3, in <module>
_input = enso.providers.getInterface( "input" )
File "C:\oreyes\apps\enso\enso-read-only\enso\providers.py", line 137, in getInterface
interface = provider.provideInterface( name )
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\__init__.py", line 48, in provideInterface
import enso.platform.win32.input
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\input\__init__.py", line 3, in <module>
from InputManager import *
File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\input\InputManager.py", line 7, in <module>
import _InputManager
ImportError: DLL load failed: Error en una rutina de inicializaci¾n de biblioteca de vÃnculos dinÃmicos (DLL).
</code></pre>
| 2 | 2008-10-21T05:57:08Z | 222,263 | <p>Looking at your update, it looks like you need to install <a href="http://www.cairographics.org/pycairo/" rel="nofollow">Pycairo</a> since you're missing the _cairo module installed as part of Pycairo. See the <a href="http://www.cairographics.org/download/" rel="nofollow">Pycairo downloads page</a> for instructions on how to obtain/install binaries for Windows.</p>
| 2 | 2008-10-21T15:18:38Z | [
"python",
"swig",
"scons",
"dynamic-linking"
] |
What is the best way on python 2.3 for windows to execute a program like ghostscript with multiple arguments and spaces in paths? | 221,097 | <p>Surely there is some kind of abstraction that allows for this?</p>
<p>This is essentially the command</p>
<blockquote>
<blockquote>
<p>cmd = self._ghostscriptPath + 'gswin32c -q -dNOPAUSE -dBATCH -sDEVICE=tiffg4 -r196X204 -sPAPERSIZE=a4 -sOutputFile="' + tifDest + " " + pdfSource + '"'</p>
<p>os.popen(cmd)</p>
</blockquote>
</blockquote>
<p>this way looks really dirty to me, there must be some pythonic way</p>
| 3 | 2008-10-21T07:56:33Z | 221,113 | <p>Use <a href="http://docs.python.org/library/subprocess" rel="nofollow">subprocess</a>, it superseeds os.popen, though it is not much more of an abstraction:</p>
<pre><code>from subprocess import Popen, PIPE
output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
#this is how I'd mangle the arguments together
output = Popen([
self._ghostscriptPath,
'gswin32c',
'-q',
'-dNOPAUSE',
'-dBATCH',
'-sDEVICE=tiffg4',
'-r196X204',
'-sPAPERSIZE=a4',
'-sOutputFile="%s %s"' % (tifDest, pdfSource),
], stdout=PIPE).communicate()[0]
</code></pre>
<p>If you have only python 2.3 which has no subprocess module, you can still use os.popen</p>
<pre><code>os.popen(' '.join([
self._ghostscriptPath,
'gswin32c',
'-q',
'-dNOPAUSE',
'-dBATCH',
'-sDEVICE=tiffg4',
'-r196X204',
'-sPAPERSIZE=a4',
'-sOutputFile="%s %s"' % (tifDest, pdfSource),
]))
</code></pre>
| 4 | 2008-10-21T08:00:56Z | [
"python",
"windows",
"ghostscript"
] |
How can I write a method within a Django model to retrieve related objects? | 221,328 | <p>I have two models. We'll call them object A and object B. Their design looks something like this:</p>
<pre><code>class Foo(models.Model):
name = models.CharField()
class Bar(models.Model):
title = models.CharField()
Foo= models.ForeignKey('myapp.Foo')
</code></pre>
<p>Now, suppose I want to make a method within Foo that returns all Bar objects that reference that instance of Foo. How do I do this?</p>
<pre><code>class Foo(models.Model):
name = models.CharField()
def returnBars(self):
????
</code></pre>
| 2 | 2008-10-21T09:49:04Z | 221,338 | <p>You get this for free:</p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects</a></p>
<p>By default, you can access a Manager which gives you access to related items through a <code>RELATEDCLASSNAME_set</code> attribute:</p>
<pre><code>some_foo.bar_set.all()
</code></pre>
<p>Or you can use the <code>related_name</code> argument to <code>ForeignKey</code> to specify the attribute which should hold the reverse relationship Manager:</p>
<pre><code>class Foo(models.Model):
name = models.CharField()
class Bar(models.Model):
title = models.CharField()
foo = models.ForeignKey(Foo, related_name='bars')
...
some_foo.bars.all()
</code></pre>
| 10 | 2008-10-21T09:54:58Z | [
"python",
"django",
"model-view-controller",
"frameworks"
] |
Is it possible to implement Python code-completion in TextMate? | 221,339 | <p><a href="http://github.com/orestis/pysmell/tree/master" rel="nofollow">PySmell</a> seems like a good starting point.</p>
<p>I think it should be possible, PySmell's <code>idehelper.py</code> does a majority of the complex stuff, it should just be a case of giving it the current line, offering up the completions (the bit I am not sure about) and then replacing the line with the selected one.</p>
<pre><code>>>> import idehelper
>>> # The path is where my PYSMELLTAGS file is located:
>>> PYSMELLDICT = idehelper.findPYSMELLDICT("/Users/dbr/Desktop/pysmell/")
>>> options = idehelper.detectCompletionType("", "" 1, 2, "", PYSMELLDICT)
>>> completions = idehelper.findCompletions("proc", PYSMELLDICT, options)
>>> print completions
[{'dup': '1', 'menu': 'pysmell.pysmell', 'kind': 'f', 'word': 'process', 'abbr': 'process(argList, excluded, output, verbose=False)'}]
</code></pre>
<p>It'll never be perfect, but it would be extremely useful (even if just for completing the stdlib modules, which should never change, so you wont have to constantly regenerate the PYSMELLTAGS file whenever you add a function)</p>
<p><hr /></p>
<p>Progressing! I have the utter-basics of completion in place - barely works, but it's close..</p>
<p>I ran <code>python pysmells.py /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/*.py -O /Library/Python/2.5/site-packages/pysmell/PYSMELLTAGS</code></p>
<p>Place the following in a TextMate bundle script, set "input: entire document", "output: insert as text", "activation: key equivalent: alt+esc", "scope selector: source.python"</p>
<pre><code>#!/usr/bin/env python
import os
import sys
from pysmell import idehelper
CUR_WORD = os.environ.get("TM_CURRENT_WORD")
cur_file = os.environ.get("TM_FILEPATH")
orig_source = sys.stdin.read()
line_no = int(os.environ.get("TM_LINE_NUMBER"))
cur_col = int(os.environ.get("TM_LINE_INDEX"))
# PYSMELLS is currently in site-packages/pysmell/
PYSMELLDICT = idehelper.findPYSMELLDICT("/Library/Python/2.5/site-packages/pysmell/blah")
options = idehelper.detectCompletionType(cur_file, orig_source, line_no, cur_col, "", PYSMELLDICT)
completions = idehelper.findCompletions(CUR_WORD, PYSMELLDICT, options)
if len(completions) > 0:
new_word = completions[0]['word']
new_word = new_word.replace(CUR_WORD, "", 1) # remove what user has already typed
print new_word
</code></pre>
<p>Then I made a new python document, typed "import urll" and hit alt+escape, and it completed it to "import urllib"!</p>
<p>As I said, it's entirely a work-in-progress, so don't use it yet..</p>
<p><hr /></p>
<p><em>Last update:</em></p>
<p>orestis has integrated this into the PySmell project's code! Any further fiddling will happen <a href="http://github.com/orestis/pysmell/tree/master" rel="nofollow">on github</a></p>
| 20 | 2008-10-21T09:54:58Z | 221,609 | <p>This isn't exactly what you're looking for but it might be able to get you started:</p>
<p><a href="http://code.djangoproject.com/wiki/TextMate" rel="nofollow">Using TextMate with Django</a></p>
<p>They appear to be somewhat Django specific but some snippets may assist with your needs. You also may be able to build on top of that with PySmells.</p>
| 3 | 2008-10-21T12:06:28Z | [
"python",
"autocomplete",
"text-editor",
"textmate"
] |
Is it possible to implement Python code-completion in TextMate? | 221,339 | <p><a href="http://github.com/orestis/pysmell/tree/master" rel="nofollow">PySmell</a> seems like a good starting point.</p>
<p>I think it should be possible, PySmell's <code>idehelper.py</code> does a majority of the complex stuff, it should just be a case of giving it the current line, offering up the completions (the bit I am not sure about) and then replacing the line with the selected one.</p>
<pre><code>>>> import idehelper
>>> # The path is where my PYSMELLTAGS file is located:
>>> PYSMELLDICT = idehelper.findPYSMELLDICT("/Users/dbr/Desktop/pysmell/")
>>> options = idehelper.detectCompletionType("", "" 1, 2, "", PYSMELLDICT)
>>> completions = idehelper.findCompletions("proc", PYSMELLDICT, options)
>>> print completions
[{'dup': '1', 'menu': 'pysmell.pysmell', 'kind': 'f', 'word': 'process', 'abbr': 'process(argList, excluded, output, verbose=False)'}]
</code></pre>
<p>It'll never be perfect, but it would be extremely useful (even if just for completing the stdlib modules, which should never change, so you wont have to constantly regenerate the PYSMELLTAGS file whenever you add a function)</p>
<p><hr /></p>
<p>Progressing! I have the utter-basics of completion in place - barely works, but it's close..</p>
<p>I ran <code>python pysmells.py /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/*.py -O /Library/Python/2.5/site-packages/pysmell/PYSMELLTAGS</code></p>
<p>Place the following in a TextMate bundle script, set "input: entire document", "output: insert as text", "activation: key equivalent: alt+esc", "scope selector: source.python"</p>
<pre><code>#!/usr/bin/env python
import os
import sys
from pysmell import idehelper
CUR_WORD = os.environ.get("TM_CURRENT_WORD")
cur_file = os.environ.get("TM_FILEPATH")
orig_source = sys.stdin.read()
line_no = int(os.environ.get("TM_LINE_NUMBER"))
cur_col = int(os.environ.get("TM_LINE_INDEX"))
# PYSMELLS is currently in site-packages/pysmell/
PYSMELLDICT = idehelper.findPYSMELLDICT("/Library/Python/2.5/site-packages/pysmell/blah")
options = idehelper.detectCompletionType(cur_file, orig_source, line_no, cur_col, "", PYSMELLDICT)
completions = idehelper.findCompletions(CUR_WORD, PYSMELLDICT, options)
if len(completions) > 0:
new_word = completions[0]['word']
new_word = new_word.replace(CUR_WORD, "", 1) # remove what user has already typed
print new_word
</code></pre>
<p>Then I made a new python document, typed "import urll" and hit alt+escape, and it completed it to "import urllib"!</p>
<p>As I said, it's entirely a work-in-progress, so don't use it yet..</p>
<p><hr /></p>
<p><em>Last update:</em></p>
<p>orestis has integrated this into the PySmell project's code! Any further fiddling will happen <a href="http://github.com/orestis/pysmell/tree/master" rel="nofollow">on github</a></p>
| 20 | 2008-10-21T09:54:58Z | 223,862 | <p>In TextMate PHP has a simple auto-completion in form of hardcoded set of function names. Sounds as ugly as PHP, but in practice it's good enough to be useful.</p>
| 0 | 2008-10-21T22:59:10Z | [
"python",
"autocomplete",
"text-editor",
"textmate"
] |
Is it possible to implement Python code-completion in TextMate? | 221,339 | <p><a href="http://github.com/orestis/pysmell/tree/master" rel="nofollow">PySmell</a> seems like a good starting point.</p>
<p>I think it should be possible, PySmell's <code>idehelper.py</code> does a majority of the complex stuff, it should just be a case of giving it the current line, offering up the completions (the bit I am not sure about) and then replacing the line with the selected one.</p>
<pre><code>>>> import idehelper
>>> # The path is where my PYSMELLTAGS file is located:
>>> PYSMELLDICT = idehelper.findPYSMELLDICT("/Users/dbr/Desktop/pysmell/")
>>> options = idehelper.detectCompletionType("", "" 1, 2, "", PYSMELLDICT)
>>> completions = idehelper.findCompletions("proc", PYSMELLDICT, options)
>>> print completions
[{'dup': '1', 'menu': 'pysmell.pysmell', 'kind': 'f', 'word': 'process', 'abbr': 'process(argList, excluded, output, verbose=False)'}]
</code></pre>
<p>It'll never be perfect, but it would be extremely useful (even if just for completing the stdlib modules, which should never change, so you wont have to constantly regenerate the PYSMELLTAGS file whenever you add a function)</p>
<p><hr /></p>
<p>Progressing! I have the utter-basics of completion in place - barely works, but it's close..</p>
<p>I ran <code>python pysmells.py /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/*.py -O /Library/Python/2.5/site-packages/pysmell/PYSMELLTAGS</code></p>
<p>Place the following in a TextMate bundle script, set "input: entire document", "output: insert as text", "activation: key equivalent: alt+esc", "scope selector: source.python"</p>
<pre><code>#!/usr/bin/env python
import os
import sys
from pysmell import idehelper
CUR_WORD = os.environ.get("TM_CURRENT_WORD")
cur_file = os.environ.get("TM_FILEPATH")
orig_source = sys.stdin.read()
line_no = int(os.environ.get("TM_LINE_NUMBER"))
cur_col = int(os.environ.get("TM_LINE_INDEX"))
# PYSMELLS is currently in site-packages/pysmell/
PYSMELLDICT = idehelper.findPYSMELLDICT("/Library/Python/2.5/site-packages/pysmell/blah")
options = idehelper.detectCompletionType(cur_file, orig_source, line_no, cur_col, "", PYSMELLDICT)
completions = idehelper.findCompletions(CUR_WORD, PYSMELLDICT, options)
if len(completions) > 0:
new_word = completions[0]['word']
new_word = new_word.replace(CUR_WORD, "", 1) # remove what user has already typed
print new_word
</code></pre>
<p>Then I made a new python document, typed "import urll" and hit alt+escape, and it completed it to "import urllib"!</p>
<p>As I said, it's entirely a work-in-progress, so don't use it yet..</p>
<p><hr /></p>
<p><em>Last update:</em></p>
<p>orestis has integrated this into the PySmell project's code! Any further fiddling will happen <a href="http://github.com/orestis/pysmell/tree/master" rel="nofollow">on github</a></p>
| 20 | 2008-10-21T09:54:58Z | 248,819 | <p>EDIT: I've actually took your code above and integrated into a command. It will properly show a completion list for you to choose.</p>
<p>You can grab it here: <a href="http://github.com/orestis/pysmell/tree/master" rel="nofollow">http://github.com/orestis/pysmell/tree/master</a> (hit download and do python setup.py install). It's rough but it works. - please report any errors on <a href="http://code.google.com/p/pysmell/" rel="nofollow">http://code.google.com/p/pysmell/</a></p>
<p>--</p>
<p>Hi, I'm the developer of PySmell. I also use a Mac, so if you can send me an email (contact info is in the source code) with your progress so far, I can try to integrate it :)</p>
<p>Oh BTW it's called PySmell - no trailing 's' :)</p>
| 9 | 2008-10-29T23:42:15Z | [
"python",
"autocomplete",
"text-editor",
"textmate"
] |
Is it possible to implement Python code-completion in TextMate? | 221,339 | <p><a href="http://github.com/orestis/pysmell/tree/master" rel="nofollow">PySmell</a> seems like a good starting point.</p>
<p>I think it should be possible, PySmell's <code>idehelper.py</code> does a majority of the complex stuff, it should just be a case of giving it the current line, offering up the completions (the bit I am not sure about) and then replacing the line with the selected one.</p>
<pre><code>>>> import idehelper
>>> # The path is where my PYSMELLTAGS file is located:
>>> PYSMELLDICT = idehelper.findPYSMELLDICT("/Users/dbr/Desktop/pysmell/")
>>> options = idehelper.detectCompletionType("", "" 1, 2, "", PYSMELLDICT)
>>> completions = idehelper.findCompletions("proc", PYSMELLDICT, options)
>>> print completions
[{'dup': '1', 'menu': 'pysmell.pysmell', 'kind': 'f', 'word': 'process', 'abbr': 'process(argList, excluded, output, verbose=False)'}]
</code></pre>
<p>It'll never be perfect, but it would be extremely useful (even if just for completing the stdlib modules, which should never change, so you wont have to constantly regenerate the PYSMELLTAGS file whenever you add a function)</p>
<p><hr /></p>
<p>Progressing! I have the utter-basics of completion in place - barely works, but it's close..</p>
<p>I ran <code>python pysmells.py /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/*.py -O /Library/Python/2.5/site-packages/pysmell/PYSMELLTAGS</code></p>
<p>Place the following in a TextMate bundle script, set "input: entire document", "output: insert as text", "activation: key equivalent: alt+esc", "scope selector: source.python"</p>
<pre><code>#!/usr/bin/env python
import os
import sys
from pysmell import idehelper
CUR_WORD = os.environ.get("TM_CURRENT_WORD")
cur_file = os.environ.get("TM_FILEPATH")
orig_source = sys.stdin.read()
line_no = int(os.environ.get("TM_LINE_NUMBER"))
cur_col = int(os.environ.get("TM_LINE_INDEX"))
# PYSMELLS is currently in site-packages/pysmell/
PYSMELLDICT = idehelper.findPYSMELLDICT("/Library/Python/2.5/site-packages/pysmell/blah")
options = idehelper.detectCompletionType(cur_file, orig_source, line_no, cur_col, "", PYSMELLDICT)
completions = idehelper.findCompletions(CUR_WORD, PYSMELLDICT, options)
if len(completions) > 0:
new_word = completions[0]['word']
new_word = new_word.replace(CUR_WORD, "", 1) # remove what user has already typed
print new_word
</code></pre>
<p>Then I made a new python document, typed "import urll" and hit alt+escape, and it completed it to "import urllib"!</p>
<p>As I said, it's entirely a work-in-progress, so don't use it yet..</p>
<p><hr /></p>
<p><em>Last update:</em></p>
<p>orestis has integrated this into the PySmell project's code! Any further fiddling will happen <a href="http://github.com/orestis/pysmell/tree/master" rel="nofollow">on github</a></p>
| 20 | 2008-10-21T09:54:58Z | 428,145 | <p>It's not perfect, but you can give it a try: <a href="http://mtod.org/tempy" rel="nofollow">http://mtod.org/tempy</a></p>
| 1 | 2009-01-09T14:04:59Z | [
"python",
"autocomplete",
"text-editor",
"textmate"
] |
Putting Copyright Symbol into a Python File | 221,376 | <p>I need to include a copyright statement at the top of every Python source file I produce:</p>
<pre><code># Copyright: © 2008 etc.
</code></pre>
<p>However, when I then run such a file I get this message:</p>
<p>SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see <a href="http://www.python.org/peps/pep-0263.html" rel="nofollow">http://www.python.org/peps/pep-0263.html</a> for details.</p>
<p>Apparently Python isn't happy about the copyright symbol because it assumes the source file is all in ASCII. Either I need to make my first line be:</p>
<pre><code># -*- coding: iso-8859-1 -*-
</code></pre>
<p>to tell Python I'm using Latin encoding, or I can change the copyright statement to: </p>
<pre><code># Copyright: \xa9 2008 etc.
</code></pre>
<p>which just possibly doesn't have the same legal standing.</p>
<p>Is there a more elegant solution?</p>
| 11 | 2008-10-21T10:15:16Z | 221,380 | <p>The copyright symbol in ASCII is spelled <code>(c)</code> or "<code>Copyright</code>".</p>
<p>See circular 61, <a href="http://www.copyright.gov/circs/circ61.pdf">Copyright Registration for Computer Programs</a>. </p>
<p>While it's true that the legal formalism (see Circular 1, <a href="http://www.copyright.gov/circs/circ01.pdf">Copyright Basics</a>) is </p>
<blockquote>
<p>The symbol © (the letter C in a
circle), or the word âCopyright,â or
the abbreviation âCopr.â; and...</p>
</blockquote>
<p>And it's also true that</p>
<blockquote>
<p>To guarantee protection for a
copyrighted work in all UCC member
countries, the notice must consist of
the symbol © (the word âCopyrightâ or
the abbreviation is not acceptable)</p>
</blockquote>
<p>You can dig through circular <a href="http://www.copyright.gov/circs/circ03.html">3</a> and <a href="http://www.copyright.gov/circs/circ38a.html">38a</a>.</p>
<p>This has, however, already been tested in court. It isn't an interesting issue. If you do a search for "(c) acceptable for c-in-a-circle", you'll find that lawyers all agree that (c) is an acceptable substitute. See Perle and Williams. See Scott on Information Technology Law.</p>
| 28 | 2008-10-21T10:17:32Z | [
"python",
"encoding"
] |
Putting Copyright Symbol into a Python File | 221,376 | <p>I need to include a copyright statement at the top of every Python source file I produce:</p>
<pre><code># Copyright: © 2008 etc.
</code></pre>
<p>However, when I then run such a file I get this message:</p>
<p>SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see <a href="http://www.python.org/peps/pep-0263.html" rel="nofollow">http://www.python.org/peps/pep-0263.html</a> for details.</p>
<p>Apparently Python isn't happy about the copyright symbol because it assumes the source file is all in ASCII. Either I need to make my first line be:</p>
<pre><code># -*- coding: iso-8859-1 -*-
</code></pre>
<p>to tell Python I'm using Latin encoding, or I can change the copyright statement to: </p>
<pre><code># Copyright: \xa9 2008 etc.
</code></pre>
<p>which just possibly doesn't have the same legal standing.</p>
<p>Is there a more elegant solution?</p>
| 11 | 2008-10-21T10:15:16Z | 221,381 | <p>You can always revert to good old (c)</p>
| 2 | 2008-10-21T10:17:51Z | [
"python",
"encoding"
] |
Putting Copyright Symbol into a Python File | 221,376 | <p>I need to include a copyright statement at the top of every Python source file I produce:</p>
<pre><code># Copyright: © 2008 etc.
</code></pre>
<p>However, when I then run such a file I get this message:</p>
<p>SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see <a href="http://www.python.org/peps/pep-0263.html" rel="nofollow">http://www.python.org/peps/pep-0263.html</a> for details.</p>
<p>Apparently Python isn't happy about the copyright symbol because it assumes the source file is all in ASCII. Either I need to make my first line be:</p>
<pre><code># -*- coding: iso-8859-1 -*-
</code></pre>
<p>to tell Python I'm using Latin encoding, or I can change the copyright statement to: </p>
<pre><code># Copyright: \xa9 2008 etc.
</code></pre>
<p>which just possibly doesn't have the same legal standing.</p>
<p>Is there a more elegant solution?</p>
| 11 | 2008-10-21T10:15:16Z | 221,543 | <p>Waiting for <a href="http://docs.python.org/dev/3.0/whatsnew/3.0.html" rel="nofollow">Python 3k</a>, where the default encoding of the source will be UTF-8?</p>
| 2 | 2008-10-21T11:40:55Z | [
"python",
"encoding"
] |
Putting Copyright Symbol into a Python File | 221,376 | <p>I need to include a copyright statement at the top of every Python source file I produce:</p>
<pre><code># Copyright: © 2008 etc.
</code></pre>
<p>However, when I then run such a file I get this message:</p>
<p>SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see <a href="http://www.python.org/peps/pep-0263.html" rel="nofollow">http://www.python.org/peps/pep-0263.html</a> for details.</p>
<p>Apparently Python isn't happy about the copyright symbol because it assumes the source file is all in ASCII. Either I need to make my first line be:</p>
<pre><code># -*- coding: iso-8859-1 -*-
</code></pre>
<p>to tell Python I'm using Latin encoding, or I can change the copyright statement to: </p>
<pre><code># Copyright: \xa9 2008 etc.
</code></pre>
<p>which just possibly doesn't have the same legal standing.</p>
<p>Is there a more elegant solution?</p>
| 11 | 2008-10-21T10:15:16Z | 221,569 | <p>Contrary to the accepted answer, AFAIK, (c) is not an officially recognized alternative to the copyright symbol, although I'm not sure it's been tested in court.</p>
<p>However, © is just an abreviation of the word Copyright. Saying "Copyright 2008 Robert Munro" is identical to saying "© 2008 Robert Munro"</p>
<p>Your "Copyright: © 2008 etc." Expands to "Copyright: Copyright 2008 etc."</p>
<p>Wikipedia's page seems to agree with me <a href="http://en.wikipedia.org/wiki/Copyright_symbol" rel="nofollow">http://en.wikipedia.org/wiki/Copyright_symbol</a></p>
<p>In the United States, the copyright notice consists of three elements:
1. the © symbol, <strong>or</strong> the word "Copyright" or abbreviation "Copr.";
...</p>
| 8 | 2008-10-21T11:50:53Z | [
"python",
"encoding"
] |
Putting Copyright Symbol into a Python File | 221,376 | <p>I need to include a copyright statement at the top of every Python source file I produce:</p>
<pre><code># Copyright: © 2008 etc.
</code></pre>
<p>However, when I then run such a file I get this message:</p>
<p>SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see <a href="http://www.python.org/peps/pep-0263.html" rel="nofollow">http://www.python.org/peps/pep-0263.html</a> for details.</p>
<p>Apparently Python isn't happy about the copyright symbol because it assumes the source file is all in ASCII. Either I need to make my first line be:</p>
<pre><code># -*- coding: iso-8859-1 -*-
</code></pre>
<p>to tell Python I'm using Latin encoding, or I can change the copyright statement to: </p>
<pre><code># Copyright: \xa9 2008 etc.
</code></pre>
<p>which just possibly doesn't have the same legal standing.</p>
<p>Is there a more elegant solution?</p>
| 11 | 2008-10-21T10:15:16Z | 221,594 | <p>Answers to this <a href="http://stackoverflow.com/questions/201837/do-you-put-copyright-notices-in-your-proprietary-code" rel="nofollow" title="Do you put copyright notices in your proprietary code?">question</a>, particularly @<a href="http://stackoverflow.com/questions/201837/do-you-put-copyright-notices-in-your-proprietary-code#201899">Ben Combee's</a> answer, should be helpful.</p>
| 0 | 2008-10-21T12:01:50Z | [
"python",
"encoding"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.