title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
|---|---|---|---|---|---|---|---|---|---|
Is there a python library that implements both sides of the AWS authentication protocol?
| 701,789
|
<p>I am writing a REST service in python and django and wanted to use Amazon's AWS authentication protocol. I was wondering if anyone knew of a python library that implemented formation of the header for sending and the validation of the header for recieving?</p>
| 3
|
2009-03-31T16:09:48Z
| 1,679,235
|
<p>I think this <a href="http://staff.science.uva.nl/~otsur/code/AWS%5FSignatureGenerator.py" rel="nofollow">code</a> does exactly what you want :)
I'll be happy to get comments for improvement if needed. </p>
| 0
|
2009-11-05T09:00:05Z
|
[
"python",
"amazon-web-services"
] |
How do I execute a string containing Python code in Python?
| 701,802
|
<p>How do I execute a string containing Python code in Python?</p>
| 156
|
2009-03-31T16:12:20Z
| 701,807
|
<p>Use <a href="http://docs.python.org/library/functions.html" rel="nofollow">eval</a>.</p>
| 2
|
2009-03-31T16:13:49Z
|
[
"python",
"string",
"exec"
] |
How do I execute a string containing Python code in Python?
| 701,802
|
<p>How do I execute a string containing Python code in Python?</p>
| 156
|
2009-03-31T16:12:20Z
| 701,808
|
<p>Check out <a href="http://docs.python.org/library/functions.html#eval" rel="nofollow">eval</a>:</p>
<pre><code>x = 1
print eval('x+1')
->2
</code></pre>
| 3
|
2009-03-31T16:14:05Z
|
[
"python",
"string",
"exec"
] |
How do I execute a string containing Python code in Python?
| 701,802
|
<p>How do I execute a string containing Python code in Python?</p>
| 156
|
2009-03-31T16:12:20Z
| 701,810
|
<p>In the example a string is executed as code using the exec function.</p>
<pre><code>import sys
import StringIO
# create file-like string to capture output
codeOut = StringIO.StringIO()
codeErr = StringIO.StringIO()
code = """
def f(x):
x = x + 1
return x
print 'This is my output.'
"""
# capture output and errors
sys.stdout = codeOut
sys.stderr = codeErr
exec code
# restore stdout and stderr
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
print f(4)
s = codeErr.getvalue()
print "error:\n%s\n" % s
s = codeOut.getvalue()
print "output:\n%s" % s
codeOut.close()
codeErr.close()
</code></pre>
| 37
|
2009-03-31T16:14:38Z
|
[
"python",
"string",
"exec"
] |
How do I execute a string containing Python code in Python?
| 701,802
|
<p>How do I execute a string containing Python code in Python?</p>
| 156
|
2009-03-31T16:12:20Z
| 701,811
|
<p>The most logical solution would be to use the built-in <a href="http://docs.python.org/library/functions.html#eval" rel="nofollow">eval()</a> function .Another solution is to write that string to a temporary python file and execute it. </p>
| 1
|
2009-03-31T16:15:10Z
|
[
"python",
"string",
"exec"
] |
How do I execute a string containing Python code in Python?
| 701,802
|
<p>How do I execute a string containing Python code in Python?</p>
| 156
|
2009-03-31T16:12:20Z
| 701,813
|
<p>For statements, use <a href="https://docs.python.org/library/functions.html#exec" rel="nofollow"><code>exec(string)</code></a> (Python 2/3) or <a href="https://docs.python.org/2/reference/simple_stmts.html#grammar-token-exec_stmt" rel="nofollow"><code>exec string</code></a> (Python 2):</p>
<pre><code>>>> mycode = 'print "hello world"'
>>> exec(mycode)
Hello world
</code></pre>
<p>When you need the value of an expression, use <a href="http://docs.python.org/library/functions.html#eval" rel="nofollow"><code>eval(string)</code></a>:</p>
<pre><code>>>> x = eval("2+2")
>>> x
4
</code></pre>
<p>However, the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It's slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.</p>
| 169
|
2009-03-31T16:15:24Z
|
[
"python",
"string",
"exec"
] |
How do I execute a string containing Python code in Python?
| 701,802
|
<p>How do I execute a string containing Python code in Python?</p>
| 156
|
2009-03-31T16:12:20Z
| 4,278,878
|
<p><code>eval()</code> is just for expressions, while <code>eval('x+1')</code> works, <code>eval('x=1')</code> won't work for example. In that case, it's better to use <code>exec</code>, or even better: try to find a better solution :)</p>
| 11
|
2010-11-25T16:03:11Z
|
[
"python",
"string",
"exec"
] |
How do I execute a string containing Python code in Python?
| 701,802
|
<p>How do I execute a string containing Python code in Python?</p>
| 156
|
2009-03-31T16:12:20Z
| 11,551,525
|
<p>You accomplish executing code using exec, as with the following IDLE session:</p>
<pre><code>>>> kw = {}
>>> exec( "ret = 4" ) in kw
>>> kw['ret']
4
</code></pre>
| 7
|
2012-07-18T22:51:49Z
|
[
"python",
"string",
"exec"
] |
How do I execute a string containing Python code in Python?
| 701,802
|
<p>How do I execute a string containing Python code in Python?</p>
| 156
|
2009-03-31T16:12:20Z
| 14,926,430
|
<p><code>eval</code> and <code>exec</code> are the correct solution, and they can be used in a safe manner!</p>
<p>As discussed in <a href="http://docs.python.org/2/reference/simple_stmts.html#exec">Python's reference manual</a> and clearly explained in <a href="http://lybniz2.sourceforge.net/safeeval.html">this</a> tutorial, the <code>eval</code> and <code>exec</code> functions take two extra parameters that allow a user to specify what global and local functions and variables are available.</p>
<p>For example:</p>
<pre><code>public_variable = 10
private_variable = 2
def public_function():
return "public information"
def private_function():
return "super sensitive information"
# make a list of safe functions
safe_list = ['public_variable', 'public_function']
safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ])
# add any needed builtins back in
safe_dict['len'] = len
>>> eval("public_variable+2", {"__builtins__" : None }, safe_dict)
12
>>> eval("private_variable+2", {"__builtins__" : None }, safe_dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'private_variable' is not defined
>>> exec("print \"'%s' has %i characters\" % (public_function(), len(public_function()))", {"__builtins__" : None}, safe_dict)
'public information' has 18 characters
>>> exec("print \"'%s' has %i characters\" % (private_function(), len(private_function()))", {"__builtins__" : None}, safe_dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'private_function' is not defined
</code></pre>
<p>In essence you are defining the namespace in which the code will be executed.</p>
| 8
|
2013-02-17T21:44:32Z
|
[
"python",
"string",
"exec"
] |
How do I execute a string containing Python code in Python?
| 701,802
|
<p>How do I execute a string containing Python code in Python?</p>
| 156
|
2009-03-31T16:12:20Z
| 17,378,416
|
<p>Remember that from version 3 <code>exec</code> is a function!<br>
so always use <code>exec(mystring)</code> instead of <code>exec mystring</code>.</p>
| 17
|
2013-06-29T08:49:04Z
|
[
"python",
"string",
"exec"
] |
How do I execute a string containing Python code in Python?
| 701,802
|
<p>How do I execute a string containing Python code in Python?</p>
| 156
|
2009-03-31T16:12:20Z
| 35,707,442
|
<h1>Avoid <code>exec</code> and <code>eval</code></h1>
<h2>Using <code>exec</code> and <code>eval</code> in Python is highly frowned upon.</h2>
<h3>There are better alternatives</h3>
<p>From the top answer (emphasis mine):</p>
<blockquote>
<p>For statements, use <code>exec</code>.</p>
<p>When you need the value of an expression, use <code>eval</code>.</p>
<p>However, the first step should be to ask yourself if you really need to. <strong>Executing code should generally be the position of last resort</strong>: It's slow, ugly and dangerous if it can contain user-entered code. You should always look at <strong>alternatives first, such as higher order functions</strong>, to see if these can better meet your needs.</p>
</blockquote>
<p>From <a href="http://stackoverflow.com/questions/16768195/alternatives-to-exec-eval">Alternatives to exec/eval?</a></p>
<blockquote>
<p>set and get values of variables with the names in strings</p>
<p>[while <code>eval</code>] would work, it is generally not advised to use variable names bearing a meaning to the program itself.</p>
<p>Instead, better use a dict.</p>
</blockquote>
<h3>It is not idiomatic</h3>
<p>From <a href="http://lucumr.pocoo.org/2011/2/1/exec-in-python/" rel="nofollow">http://lucumr.pocoo.org/2011/2/1/exec-in-python/</a> (emphasis mine)</p>
<blockquote>
<h3>Python is not PHP</h3>
<p>Don't try to circumvent Python idioms because some other language does it differently. Namespaces are in Python for a reason and <strong>just because it gives you the tool <code>exec</code> it does not mean you should use that tool.</strong></p>
</blockquote>
<h3>It is dangerous</h3>
<p>From <a href="http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html" rel="nofollow">http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html</a> (emphasis mine)</p>
<blockquote>
<p>So eval is not safe, even if you remove all the globals and the builtins!</p>
<p>The problem with all of these <strong>attempts to protect eval() is that they are blacklists</strong>. They explicitly remove things that could be dangerous. That is a losing battle because <strong>if there's just one item left off the list, you can attack the system</strong>.</p>
<p>So, can eval be made safe? Hard to say. At this point, my best guess is that you can't do any harm if you can't use any double underscores, so maybe if you exclude any string with double underscores you are safe. Maybe...</p>
</blockquote>
<h3>It is hard to read and understand</h3>
<p>From <a href="http://stupidpythonideas.blogspot.it/2013/05/why-evalexec-is-bad.html" rel="nofollow">http://stupidpythonideas.blogspot.it/2013/05/why-evalexec-is-bad.html</a> (emphasis mine):</p>
<blockquote>
<p>First, <strong><code>exec</code> makes it harder to human beings to read your code</strong>. In order to figure out what's happening, I don't just have to read your code, <strong>I have to read your code, figure out what string it's going to generate, then read that virtual code.</strong> So, if you're working on a team, or publishing open source software, or asking for help somewhere like StackOverflow, you're making it harder for other people to help you. And if there's any chance that you're going to be debugging or expanding on this code 6 months from now, you're making it harder for yourself directly.</p>
</blockquote>
| 2
|
2016-02-29T19:01:54Z
|
[
"python",
"string",
"exec"
] |
Django Model.object.get pre_save Function Weirdness
| 702,150
|
<p>I have made a function that connects to a models 'pre_save' signal. Inside the function I am trying to check if the model instance's pk already exists in the table with:</p>
<pre><code>sender.objects.get(pk=instance._get_pk_val())
</code></pre>
<p>The first instance of the model raises an error. I catch the error and generate a slug field from the title. In a second instance, it doesn't throw the error. I checked the value of instance._get_pk_val() on both instances and they are the same: None</p>
<p>So:</p>
<pre><code># This one raises an error in the sluggit function
instance1 = Model(title="title 1")
instance1.save()
# This one doesn't raise an error
instance2 = Model(title="title 2")
instance2.save()
</code></pre>
<p>This is my 3rd day messing around with python and django. So I am sorry if it something newbish that I am not seeing.</p>
<p><strong>Edit:</strong> </p>
<p>The Model:</p>
<pre><code>class Test(models.Model):
title = models.CharField(max_length=128)
slug = models.SlugField(max_length=128)
slug.prepopulate_from=('title',)
signals.pre_save.connect(package.sluggit, sender=Test)
</code></pre>
<p>The Function Basics:</p>
<pre><code>def sluggit(sender, instance, signal, *args, **kwargs):
try:
sender.objects.get(pk=instance._get_pk_val())
except:
# Generate Slug Code
</code></pre>
<p>@S.Lot told me to override the save() method in the comments. I'll have to try that. I would still like to know why the second call to model.objects.get() isn't raising an error with this method.</p>
<p><strong>Edit 2</strong>
Thank you @S.Lot. Overriding the save method works perfectly. Still curious about the signal method. Hmm, weird.</p>
<p><strong>Edit 3</strong>
After playing around a little more, I found that using instance.objects.get() instead of sender.objects.get() works:</p>
<pre><code>def sluggit(sender, instance, signal, *args, **kwargs):
try:
sender.objects.get(pk=instance._get_pk_val())
except:
# Generate Slug Code
</code></pre>
<p>needs to be:</p>
<pre><code>def sluggit(sender, instance, signal, *args, **kwargs):
try:
instance.objects.get(pk=instance._get_pk_val())
except:
# Generate Slug Code
</code></pre>
<p>A bug? For some reason I thought sender.objects.get() would be the same as Test.objects.get().</p>
| 2
|
2009-03-31T17:29:39Z
| 702,630
|
<p>S.Lott is correct... use <code>save()</code>, as you've already acknowledged that you have started doing.</p>
<p>As for the signal question, I can honestly see nothing wrong with your code. I've even run it locally myself with success. Are you sure that you're representing it properly in the question? Or that instance2 isn't already an existing database object (perhaps a goof in your test code)?</p>
| 1
|
2009-03-31T19:19:18Z
|
[
"python",
"django",
"django-models",
"error-handling",
"django-signals"
] |
Django Model.object.get pre_save Function Weirdness
| 702,150
|
<p>I have made a function that connects to a models 'pre_save' signal. Inside the function I am trying to check if the model instance's pk already exists in the table with:</p>
<pre><code>sender.objects.get(pk=instance._get_pk_val())
</code></pre>
<p>The first instance of the model raises an error. I catch the error and generate a slug field from the title. In a second instance, it doesn't throw the error. I checked the value of instance._get_pk_val() on both instances and they are the same: None</p>
<p>So:</p>
<pre><code># This one raises an error in the sluggit function
instance1 = Model(title="title 1")
instance1.save()
# This one doesn't raise an error
instance2 = Model(title="title 2")
instance2.save()
</code></pre>
<p>This is my 3rd day messing around with python and django. So I am sorry if it something newbish that I am not seeing.</p>
<p><strong>Edit:</strong> </p>
<p>The Model:</p>
<pre><code>class Test(models.Model):
title = models.CharField(max_length=128)
slug = models.SlugField(max_length=128)
slug.prepopulate_from=('title',)
signals.pre_save.connect(package.sluggit, sender=Test)
</code></pre>
<p>The Function Basics:</p>
<pre><code>def sluggit(sender, instance, signal, *args, **kwargs):
try:
sender.objects.get(pk=instance._get_pk_val())
except:
# Generate Slug Code
</code></pre>
<p>@S.Lot told me to override the save() method in the comments. I'll have to try that. I would still like to know why the second call to model.objects.get() isn't raising an error with this method.</p>
<p><strong>Edit 2</strong>
Thank you @S.Lot. Overriding the save method works perfectly. Still curious about the signal method. Hmm, weird.</p>
<p><strong>Edit 3</strong>
After playing around a little more, I found that using instance.objects.get() instead of sender.objects.get() works:</p>
<pre><code>def sluggit(sender, instance, signal, *args, **kwargs):
try:
sender.objects.get(pk=instance._get_pk_val())
except:
# Generate Slug Code
</code></pre>
<p>needs to be:</p>
<pre><code>def sluggit(sender, instance, signal, *args, **kwargs):
try:
instance.objects.get(pk=instance._get_pk_val())
except:
# Generate Slug Code
</code></pre>
<p>A bug? For some reason I thought sender.objects.get() would be the same as Test.objects.get().</p>
| 2
|
2009-03-31T17:29:39Z
| 784,437
|
<p>Thanks for posting this. The top google results (at the time I'm posting this) are a little outdated and show the old way of connecting signals (which was recently rewritten, apparently). Your edits, with the corrected code snippets showed me how it's done.</p>
<p>I wish more posters edited their comments to place a fix in it. Thanks. :-)</p>
| 0
|
2009-04-24T03:48:50Z
|
[
"python",
"django",
"django-models",
"error-handling",
"django-signals"
] |
Django vs other Python web frameworks?
| 702,179
|
<p>I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with <a href="http://snakelets.sf.net">Snakelets</a> and heartily enjoyed being able to control almost everything at a lower level without much fuss, but then I discovered <a href="http://turbogears.org">TurboGears</a> and I have been using it (1.x) ever since. Tools like Catwalk and the web console are invaluable to me.</p>
<p>But with TurboGears 2 coming out which brings WSGI support, and after reading up on the religious debates between the Django and WSGI camps, I'm really torn between <strong><em>"doing it the right way"</em></strong>, e.g., learning WSGI, spending valuable time writing functionality that already exists in Django and other full-stack frameworks, as opposed to using Django or some high-level framework that does everything for me. The downsides with the latter that I can see are pretty obvious: </p>
<ol>
<li>I'm not learning anything in the process</li>
<li>If I ever need to do anything lower level it's going to be a pain</li>
<li>The overhead required for just a basic site which uses authentication is insane. (IMO)</li>
</ol>
<p>So, I guess my question is, which is the better choice, or is it just a matter of opinion, and should I suck it up and use Django if it achieves what I want with minimal fuss (I want authentication and a CRUD interface to my database)? I tried Werkzeug, Glashammer, and friends, but AuthKit and Repoze scared me off, as well as the number of steps involved to just setup basic authentication. I looked at Pylons, but the documentation seems lacking, and when referencing simple features like authentication or a CRUD interface, various wiki pages and documentation seemed to contradict each other, with different hacks for versions and such. </p>
<p><hr /></p>
<p>Thanks to S. Lott for pointing out that I wasn't clear enough. My question is: which of the following is worthwhile in the long run, but not painful in the short (e.g., some sort of middle ground, anyone?) - Learn WSGI, or stick with a "batteries-included" framework? If the latter, I would appreciate a suggestion as to whether I should give Django another try, stick with TurboGears 1.x, or venture into some other framework. </p>
<p>Also, I have tried CherryPy, but couldn't seem to find a good enough CRUD application that I could plop in and use right away.</p>
| 58
|
2009-03-31T17:39:02Z
| 702,215
|
<p>Have you taken a look at CherryPy. It is minimalistic, yet efficient and simple. It is low level enough for not it to get in they way, but high enough to hide complexity. If I remember well, TurboGears was built on it.</p>
<p>With CherryPy, you have the choice of much everything. (Template framework, ORM if wanted, back-end, etc.)</p>
| 7
|
2009-03-31T17:46:40Z
|
[
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] |
Django vs other Python web frameworks?
| 702,179
|
<p>I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with <a href="http://snakelets.sf.net">Snakelets</a> and heartily enjoyed being able to control almost everything at a lower level without much fuss, but then I discovered <a href="http://turbogears.org">TurboGears</a> and I have been using it (1.x) ever since. Tools like Catwalk and the web console are invaluable to me.</p>
<p>But with TurboGears 2 coming out which brings WSGI support, and after reading up on the religious debates between the Django and WSGI camps, I'm really torn between <strong><em>"doing it the right way"</em></strong>, e.g., learning WSGI, spending valuable time writing functionality that already exists in Django and other full-stack frameworks, as opposed to using Django or some high-level framework that does everything for me. The downsides with the latter that I can see are pretty obvious: </p>
<ol>
<li>I'm not learning anything in the process</li>
<li>If I ever need to do anything lower level it's going to be a pain</li>
<li>The overhead required for just a basic site which uses authentication is insane. (IMO)</li>
</ol>
<p>So, I guess my question is, which is the better choice, or is it just a matter of opinion, and should I suck it up and use Django if it achieves what I want with minimal fuss (I want authentication and a CRUD interface to my database)? I tried Werkzeug, Glashammer, and friends, but AuthKit and Repoze scared me off, as well as the number of steps involved to just setup basic authentication. I looked at Pylons, but the documentation seems lacking, and when referencing simple features like authentication or a CRUD interface, various wiki pages and documentation seemed to contradict each other, with different hacks for versions and such. </p>
<p><hr /></p>
<p>Thanks to S. Lott for pointing out that I wasn't clear enough. My question is: which of the following is worthwhile in the long run, but not painful in the short (e.g., some sort of middle ground, anyone?) - Learn WSGI, or stick with a "batteries-included" framework? If the latter, I would appreciate a suggestion as to whether I should give Django another try, stick with TurboGears 1.x, or venture into some other framework. </p>
<p>Also, I have tried CherryPy, but couldn't seem to find a good enough CRUD application that I could plop in and use right away.</p>
| 58
|
2009-03-31T17:39:02Z
| 702,360
|
<p>I'd say you're being a bit too pessimistic about "not learning anything" using Django or a similar full-stack framework, and underestimating the value of documentation and a large community. Even with Django there's still a considerable learning curve; and if it doesn't do everything you want, it's not like the framework code is impenetrable.</p>
<p>Some personal experience: I spent years, on and off, messing around with Twisted/Nevow, TurboGears and a few other Python web frameworks. IÂ never finished anything because the framework code was perpetually unfinished and being rewritten underneath me, the documentation was often nonexistent or wrong and the only viable support was via IRC (where I often got great advice, but felt like I was imposing if I asked too many questions).</p>
<p>By comparison, in the past couple of years I've knocked off a few sites with Django. Unlike my previous experience, they're actually deployed and running. The Django development process may be slow and careful, but it results in much less bitrot and deprecation, and documentation that is actually helpful.</p>
<p>HTTP authentication support for Django <a href="http://code.djangoproject.com/ticket/689">finally went in</a> a few weeks ago, if that's what you're referring to in #3.</p>
| 21
|
2009-03-31T18:11:31Z
|
[
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] |
Django vs other Python web frameworks?
| 702,179
|
<p>I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with <a href="http://snakelets.sf.net">Snakelets</a> and heartily enjoyed being able to control almost everything at a lower level without much fuss, but then I discovered <a href="http://turbogears.org">TurboGears</a> and I have been using it (1.x) ever since. Tools like Catwalk and the web console are invaluable to me.</p>
<p>But with TurboGears 2 coming out which brings WSGI support, and after reading up on the religious debates between the Django and WSGI camps, I'm really torn between <strong><em>"doing it the right way"</em></strong>, e.g., learning WSGI, spending valuable time writing functionality that already exists in Django and other full-stack frameworks, as opposed to using Django or some high-level framework that does everything for me. The downsides with the latter that I can see are pretty obvious: </p>
<ol>
<li>I'm not learning anything in the process</li>
<li>If I ever need to do anything lower level it's going to be a pain</li>
<li>The overhead required for just a basic site which uses authentication is insane. (IMO)</li>
</ol>
<p>So, I guess my question is, which is the better choice, or is it just a matter of opinion, and should I suck it up and use Django if it achieves what I want with minimal fuss (I want authentication and a CRUD interface to my database)? I tried Werkzeug, Glashammer, and friends, but AuthKit and Repoze scared me off, as well as the number of steps involved to just setup basic authentication. I looked at Pylons, but the documentation seems lacking, and when referencing simple features like authentication or a CRUD interface, various wiki pages and documentation seemed to contradict each other, with different hacks for versions and such. </p>
<p><hr /></p>
<p>Thanks to S. Lott for pointing out that I wasn't clear enough. My question is: which of the following is worthwhile in the long run, but not painful in the short (e.g., some sort of middle ground, anyone?) - Learn WSGI, or stick with a "batteries-included" framework? If the latter, I would appreciate a suggestion as to whether I should give Django another try, stick with TurboGears 1.x, or venture into some other framework. </p>
<p>Also, I have tried CherryPy, but couldn't seem to find a good enough CRUD application that I could plop in and use right away.</p>
| 58
|
2009-03-31T17:39:02Z
| 702,366
|
<p>Have you checked out web2py? After recently evaluating many Python web frameworks recently I've decided to adopt this one. Also check out Google App Engine if you haven't already.</p>
| 2
|
2009-03-31T18:12:33Z
|
[
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] |
Django vs other Python web frameworks?
| 702,179
|
<p>I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with <a href="http://snakelets.sf.net">Snakelets</a> and heartily enjoyed being able to control almost everything at a lower level without much fuss, but then I discovered <a href="http://turbogears.org">TurboGears</a> and I have been using it (1.x) ever since. Tools like Catwalk and the web console are invaluable to me.</p>
<p>But with TurboGears 2 coming out which brings WSGI support, and after reading up on the religious debates between the Django and WSGI camps, I'm really torn between <strong><em>"doing it the right way"</em></strong>, e.g., learning WSGI, spending valuable time writing functionality that already exists in Django and other full-stack frameworks, as opposed to using Django or some high-level framework that does everything for me. The downsides with the latter that I can see are pretty obvious: </p>
<ol>
<li>I'm not learning anything in the process</li>
<li>If I ever need to do anything lower level it's going to be a pain</li>
<li>The overhead required for just a basic site which uses authentication is insane. (IMO)</li>
</ol>
<p>So, I guess my question is, which is the better choice, or is it just a matter of opinion, and should I suck it up and use Django if it achieves what I want with minimal fuss (I want authentication and a CRUD interface to my database)? I tried Werkzeug, Glashammer, and friends, but AuthKit and Repoze scared me off, as well as the number of steps involved to just setup basic authentication. I looked at Pylons, but the documentation seems lacking, and when referencing simple features like authentication or a CRUD interface, various wiki pages and documentation seemed to contradict each other, with different hacks for versions and such. </p>
<p><hr /></p>
<p>Thanks to S. Lott for pointing out that I wasn't clear enough. My question is: which of the following is worthwhile in the long run, but not painful in the short (e.g., some sort of middle ground, anyone?) - Learn WSGI, or stick with a "batteries-included" framework? If the latter, I would appreciate a suggestion as to whether I should give Django another try, stick with TurboGears 1.x, or venture into some other framework. </p>
<p>Also, I have tried CherryPy, but couldn't seem to find a good enough CRUD application that I could plop in and use right away.</p>
| 58
|
2009-03-31T17:39:02Z
| 702,576
|
<p>Django is definitely worth learning, and sounds like it will fit your purposes. The admin interface it comes with is easy to get up and running, and it does use authentication.</p>
<p>As for "anything lower level", if you mean sql, it is entirely possible to shove sql into you queries with the extra keyword. Stylistically, you always try to avoid that as much as possible.</p>
<p>As for "not learning anything"...the real question is whether your preference is to be primarily learning something lower-level or higher-level, which is hardly a question anyone here can answer for you.</p>
| 1
|
2009-03-31T19:04:16Z
|
[
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] |
Django vs other Python web frameworks?
| 702,179
|
<p>I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with <a href="http://snakelets.sf.net">Snakelets</a> and heartily enjoyed being able to control almost everything at a lower level without much fuss, but then I discovered <a href="http://turbogears.org">TurboGears</a> and I have been using it (1.x) ever since. Tools like Catwalk and the web console are invaluable to me.</p>
<p>But with TurboGears 2 coming out which brings WSGI support, and after reading up on the religious debates between the Django and WSGI camps, I'm really torn between <strong><em>"doing it the right way"</em></strong>, e.g., learning WSGI, spending valuable time writing functionality that already exists in Django and other full-stack frameworks, as opposed to using Django or some high-level framework that does everything for me. The downsides with the latter that I can see are pretty obvious: </p>
<ol>
<li>I'm not learning anything in the process</li>
<li>If I ever need to do anything lower level it's going to be a pain</li>
<li>The overhead required for just a basic site which uses authentication is insane. (IMO)</li>
</ol>
<p>So, I guess my question is, which is the better choice, or is it just a matter of opinion, and should I suck it up and use Django if it achieves what I want with minimal fuss (I want authentication and a CRUD interface to my database)? I tried Werkzeug, Glashammer, and friends, but AuthKit and Repoze scared me off, as well as the number of steps involved to just setup basic authentication. I looked at Pylons, but the documentation seems lacking, and when referencing simple features like authentication or a CRUD interface, various wiki pages and documentation seemed to contradict each other, with different hacks for versions and such. </p>
<p><hr /></p>
<p>Thanks to S. Lott for pointing out that I wasn't clear enough. My question is: which of the following is worthwhile in the long run, but not painful in the short (e.g., some sort of middle ground, anyone?) - Learn WSGI, or stick with a "batteries-included" framework? If the latter, I would appreciate a suggestion as to whether I should give Django another try, stick with TurboGears 1.x, or venture into some other framework. </p>
<p>Also, I have tried CherryPy, but couldn't seem to find a good enough CRUD application that I could plop in and use right away.</p>
| 58
|
2009-03-31T17:39:02Z
| 702,596
|
<p>I'm a TurboGears fan, and this is exactly the reason why: a very nice trade-off between control and doing things right vs. easy.</p>
<p>You'll have to make up your own mind of course. Maybe you'd prefer to learn less, maybe more. Maybe the areas that I like knowledge/control (database for example), you couldn't care less about. And don't misunderstand. I'm not characterizing any frameworks as necessarily hard or wrong. It's just my subjective judgment.</p>
<p>Also I would recommend TurboGears 2 if at all possible. When it comes out, I think it will be much better than 1.0 in terms of what it has selected for defaults (genshi, pylons, SqlAlchemy)</p>
| 0
|
2009-03-31T19:11:10Z
|
[
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] |
Django vs other Python web frameworks?
| 702,179
|
<p>I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with <a href="http://snakelets.sf.net">Snakelets</a> and heartily enjoyed being able to control almost everything at a lower level without much fuss, but then I discovered <a href="http://turbogears.org">TurboGears</a> and I have been using it (1.x) ever since. Tools like Catwalk and the web console are invaluable to me.</p>
<p>But with TurboGears 2 coming out which brings WSGI support, and after reading up on the religious debates between the Django and WSGI camps, I'm really torn between <strong><em>"doing it the right way"</em></strong>, e.g., learning WSGI, spending valuable time writing functionality that already exists in Django and other full-stack frameworks, as opposed to using Django or some high-level framework that does everything for me. The downsides with the latter that I can see are pretty obvious: </p>
<ol>
<li>I'm not learning anything in the process</li>
<li>If I ever need to do anything lower level it's going to be a pain</li>
<li>The overhead required for just a basic site which uses authentication is insane. (IMO)</li>
</ol>
<p>So, I guess my question is, which is the better choice, or is it just a matter of opinion, and should I suck it up and use Django if it achieves what I want with minimal fuss (I want authentication and a CRUD interface to my database)? I tried Werkzeug, Glashammer, and friends, but AuthKit and Repoze scared me off, as well as the number of steps involved to just setup basic authentication. I looked at Pylons, but the documentation seems lacking, and when referencing simple features like authentication or a CRUD interface, various wiki pages and documentation seemed to contradict each other, with different hacks for versions and such. </p>
<p><hr /></p>
<p>Thanks to S. Lott for pointing out that I wasn't clear enough. My question is: which of the following is worthwhile in the long run, but not painful in the short (e.g., some sort of middle ground, anyone?) - Learn WSGI, or stick with a "batteries-included" framework? If the latter, I would appreciate a suggestion as to whether I should give Django another try, stick with TurboGears 1.x, or venture into some other framework. </p>
<p>Also, I have tried CherryPy, but couldn't seem to find a good enough CRUD application that I could plop in and use right away.</p>
| 58
|
2009-03-31T17:39:02Z
| 702,738
|
<p>I would suggest for TurboGears 2. They have done a fantastic job of integrating best of Python world. </p>
<p><strong>WSGI:</strong> Assuming you are developing moderately complex projects/ business solutions in TG2 or some other framework say Grok. Even though these frameworks supports WSGI does that mean one who is using these frameworks have to learn WSGI? In most cases answer is No. I mean it's good have this knowledge no doubt. </p>
<p>WSGI knowledge is probably is more useful in cases like</p>
<ul>
<li>you want to use some middleware or some other component which is not provided as part of the standard stack for eg. Authkit with TG or <a href="http://blog.d2m.at/2008/04/13/grok-without-zodb-wsgi-based/" rel="nofollow">Grok without ZODB</a>. </li>
<li>you are doing some integration.</li>
</ul>
<p><strong>CherryPy</strong> is good but think of handling your database commits/rollbacks at the end of transactions, exposing json, validations in such cases TG, Django like frameworks do it all for you.</p>
| 0
|
2009-03-31T19:46:54Z
|
[
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] |
Django vs other Python web frameworks?
| 702,179
|
<p>I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with <a href="http://snakelets.sf.net">Snakelets</a> and heartily enjoyed being able to control almost everything at a lower level without much fuss, but then I discovered <a href="http://turbogears.org">TurboGears</a> and I have been using it (1.x) ever since. Tools like Catwalk and the web console are invaluable to me.</p>
<p>But with TurboGears 2 coming out which brings WSGI support, and after reading up on the religious debates between the Django and WSGI camps, I'm really torn between <strong><em>"doing it the right way"</em></strong>, e.g., learning WSGI, spending valuable time writing functionality that already exists in Django and other full-stack frameworks, as opposed to using Django or some high-level framework that does everything for me. The downsides with the latter that I can see are pretty obvious: </p>
<ol>
<li>I'm not learning anything in the process</li>
<li>If I ever need to do anything lower level it's going to be a pain</li>
<li>The overhead required for just a basic site which uses authentication is insane. (IMO)</li>
</ol>
<p>So, I guess my question is, which is the better choice, or is it just a matter of opinion, and should I suck it up and use Django if it achieves what I want with minimal fuss (I want authentication and a CRUD interface to my database)? I tried Werkzeug, Glashammer, and friends, but AuthKit and Repoze scared me off, as well as the number of steps involved to just setup basic authentication. I looked at Pylons, but the documentation seems lacking, and when referencing simple features like authentication or a CRUD interface, various wiki pages and documentation seemed to contradict each other, with different hacks for versions and such. </p>
<p><hr /></p>
<p>Thanks to S. Lott for pointing out that I wasn't clear enough. My question is: which of the following is worthwhile in the long run, but not painful in the short (e.g., some sort of middle ground, anyone?) - Learn WSGI, or stick with a "batteries-included" framework? If the latter, I would appreciate a suggestion as to whether I should give Django another try, stick with TurboGears 1.x, or venture into some other framework. </p>
<p>Also, I have tried CherryPy, but couldn't seem to find a good enough CRUD application that I could plop in and use right away.</p>
| 58
|
2009-03-31T17:39:02Z
| 703,232
|
<p>I suggest taking another look at TG2. I think people have failed to notice some of the strides that have been made since the last version. Aside from the growing WSGI stack of utilities available there are quite a few TG2-specific items to consider. Here are a couple of highlights:</p>
<p><a href="http://turbogears.org/2.0/docs/main/Extensions/index.html">TurboGears Administration System</a> - This CRUD interface to your database is fully customizable using a declarative config class. It is also integrated with Dojo to give you infinitely scrollable tables. Server side validation is also automated. The admin interface uses RESTful urls and HTTP verbs which means it would be easy to connect to programatically using industry standards.</p>
<p><a href="http://turbogears.org/2.0/docs/main/Extensions/Crud/index.html">CrudRestController</a>/<a href="http://turbogears.org/2.0/docs/modules/tgcontroller.html?highlight=restcontroller#tg.controllers.RestController">RestController</a> - TurboGears provides a structured way to handle services in your controller. Providing you the ability to use standardized HTTP verbs simply by extending our RestController. Combine <a href="http://www.sprox.org">Sprox</a> with CrudRestController, and you can put crud anywhere in your application with fully-customizable autogenerated forms.
TurboGears now supports mime-types as file extensions in the url, so you can have your controller render .json and .xml with the same interface it uses to render html (returning a dictionary from a controller)</p>
<p>If you click the links you will see that we have a new set of documentation built with sphinx which is more extensive than the docs of the past.</p>
<p>With the best <a href="http://pylonshq.com">web server</a>, <a href="http://www.sqlalchemy.org">ORM</a>, and <a href="http://genshi.edgewall.org/">template system</a>(s) (pick your own) under the hood, it's easy to see why TG makes sense for people who want to get going quickly, and still have scalability as their site grows.</p>
<p>TurboGears is often seen as trying to hit a moving target, but we are consistent about releases, which means you won't have to worry about working out of the trunk to get the latest features you need. Coming to the future: more TurboGears extensions that will allow your application to grow functionality with the ease of paster commands.</p>
| 15
|
2009-03-31T21:54:24Z
|
[
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] |
Django vs other Python web frameworks?
| 702,179
|
<p>I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with <a href="http://snakelets.sf.net">Snakelets</a> and heartily enjoyed being able to control almost everything at a lower level without much fuss, but then I discovered <a href="http://turbogears.org">TurboGears</a> and I have been using it (1.x) ever since. Tools like Catwalk and the web console are invaluable to me.</p>
<p>But with TurboGears 2 coming out which brings WSGI support, and after reading up on the religious debates between the Django and WSGI camps, I'm really torn between <strong><em>"doing it the right way"</em></strong>, e.g., learning WSGI, spending valuable time writing functionality that already exists in Django and other full-stack frameworks, as opposed to using Django or some high-level framework that does everything for me. The downsides with the latter that I can see are pretty obvious: </p>
<ol>
<li>I'm not learning anything in the process</li>
<li>If I ever need to do anything lower level it's going to be a pain</li>
<li>The overhead required for just a basic site which uses authentication is insane. (IMO)</li>
</ol>
<p>So, I guess my question is, which is the better choice, or is it just a matter of opinion, and should I suck it up and use Django if it achieves what I want with minimal fuss (I want authentication and a CRUD interface to my database)? I tried Werkzeug, Glashammer, and friends, but AuthKit and Repoze scared me off, as well as the number of steps involved to just setup basic authentication. I looked at Pylons, but the documentation seems lacking, and when referencing simple features like authentication or a CRUD interface, various wiki pages and documentation seemed to contradict each other, with different hacks for versions and such. </p>
<p><hr /></p>
<p>Thanks to S. Lott for pointing out that I wasn't clear enough. My question is: which of the following is worthwhile in the long run, but not painful in the short (e.g., some sort of middle ground, anyone?) - Learn WSGI, or stick with a "batteries-included" framework? If the latter, I would appreciate a suggestion as to whether I should give Django another try, stick with TurboGears 1.x, or venture into some other framework. </p>
<p>Also, I have tried CherryPy, but couldn't seem to find a good enough CRUD application that I could plop in and use right away.</p>
| 58
|
2009-03-31T17:39:02Z
| 703,271
|
<p>Your question seems to be "is it worth learning WSGI and doing everything yourself," or using a "full stack framework that does everything for you." </p>
<p>I'd say that's a false dichotomy and there's an obvious third way. TurboGears 2 tries to provide a smooth path from a "do everything for you" style framework up to an understanding of WSGI middleware, and an ability to customize almost every aspect of the framework to suit your application's needs. </p>
<p>We may not be successful in every place at every level, but particularly if you've already got some TurboGears 1 experience I think the TG2 learning curve will be very, very easy at first and you'll have the ability to go deeper exactly when you need it. </p>
<p>To address your particular issues: </p>
<ul>
<li>We provide an authorization system out of the box that matches the one you're used to from TG1.</li>
<li>We provide an out of the box "django admin" like interface called the tgext.admin, which works great with dojo to make a fancy spreadsheet like interface the default.</li>
</ul>
<p>I'd also like to address a couple of the other options that are out there and talk a little bit about the benifits. </p>
<ul>
<li><p><strong>CherryPy.</strong> I think CherryPy is a great webserver and a nice minimalistic web-framework. It's not based on WSGI internally but has good WSGI support although it will not provide you with the "full stack" experience. But for custom setups that need to be both fast and aren't particularly suited to the defaults provided by Django or TurboGears, it's a great solution.</p></li>
<li><p><strong>Django.</strong> I think Django is a very nice, tigtly integrated system for developing websites. If your application and style of working fits well within it's standard setup it can be fantastic. If however you need to tune your DB usage, replace the template language, use a different user authorization model or otherwise do things differently you may very likely find yourself fighting the framework. </p></li>
<li><p><strong>Pylons</strong> Pylons like CherryPy is a great minimalistic web-framework. Unlike CherryPy it's WSGI enabled through the whole system and provides some sane defaults like SQLAlchemy and Mako that can help you scale well. The new official docs are of much better quality than the old wiki docs which are what you seem to have looked at. </p></li>
</ul>
| 11
|
2009-03-31T22:07:15Z
|
[
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] |
Django vs other Python web frameworks?
| 702,179
|
<p>I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with <a href="http://snakelets.sf.net">Snakelets</a> and heartily enjoyed being able to control almost everything at a lower level without much fuss, but then I discovered <a href="http://turbogears.org">TurboGears</a> and I have been using it (1.x) ever since. Tools like Catwalk and the web console are invaluable to me.</p>
<p>But with TurboGears 2 coming out which brings WSGI support, and after reading up on the religious debates between the Django and WSGI camps, I'm really torn between <strong><em>"doing it the right way"</em></strong>, e.g., learning WSGI, spending valuable time writing functionality that already exists in Django and other full-stack frameworks, as opposed to using Django or some high-level framework that does everything for me. The downsides with the latter that I can see are pretty obvious: </p>
<ol>
<li>I'm not learning anything in the process</li>
<li>If I ever need to do anything lower level it's going to be a pain</li>
<li>The overhead required for just a basic site which uses authentication is insane. (IMO)</li>
</ol>
<p>So, I guess my question is, which is the better choice, or is it just a matter of opinion, and should I suck it up and use Django if it achieves what I want with minimal fuss (I want authentication and a CRUD interface to my database)? I tried Werkzeug, Glashammer, and friends, but AuthKit and Repoze scared me off, as well as the number of steps involved to just setup basic authentication. I looked at Pylons, but the documentation seems lacking, and when referencing simple features like authentication or a CRUD interface, various wiki pages and documentation seemed to contradict each other, with different hacks for versions and such. </p>
<p><hr /></p>
<p>Thanks to S. Lott for pointing out that I wasn't clear enough. My question is: which of the following is worthwhile in the long run, but not painful in the short (e.g., some sort of middle ground, anyone?) - Learn WSGI, or stick with a "batteries-included" framework? If the latter, I would appreciate a suggestion as to whether I should give Django another try, stick with TurboGears 1.x, or venture into some other framework. </p>
<p>Also, I have tried CherryPy, but couldn't seem to find a good enough CRUD application that I could plop in and use right away.</p>
| 58
|
2009-03-31T17:39:02Z
| 703,326
|
<blockquote>
<p>the religious debates between the Django and WSGI camps</p>
</blockquote>
<p>It would seem as though you're a tad bit confused about what WSGI is and what Django is. Saying that Django and WSGI are competing is a bit like saying that C and SQL are competing: you're comparing apples and oranges.</p>
<p>Django is a framework, WSGI is a protocol (which is supported by Django) for how the server interacts with the framework. Most importantly, learning to use WSGI directly is a bit like learning assembly. It's a great learning experience, but it's not really something you should do for production code (nor was it intended to be).</p>
<p>At any rate, my advice is to figure it out for yourself. Most frameworks have a "make a wiki/blog/poll in an hour" type exercise. Spend a little time with each one and figure out which one you like best. After all, how can you decide between different frameworks if you're not willing to try them out?</p>
| 52
|
2009-03-31T22:25:31Z
|
[
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] |
Django vs other Python web frameworks?
| 702,179
|
<p>I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with <a href="http://snakelets.sf.net">Snakelets</a> and heartily enjoyed being able to control almost everything at a lower level without much fuss, but then I discovered <a href="http://turbogears.org">TurboGears</a> and I have been using it (1.x) ever since. Tools like Catwalk and the web console are invaluable to me.</p>
<p>But with TurboGears 2 coming out which brings WSGI support, and after reading up on the religious debates between the Django and WSGI camps, I'm really torn between <strong><em>"doing it the right way"</em></strong>, e.g., learning WSGI, spending valuable time writing functionality that already exists in Django and other full-stack frameworks, as opposed to using Django or some high-level framework that does everything for me. The downsides with the latter that I can see are pretty obvious: </p>
<ol>
<li>I'm not learning anything in the process</li>
<li>If I ever need to do anything lower level it's going to be a pain</li>
<li>The overhead required for just a basic site which uses authentication is insane. (IMO)</li>
</ol>
<p>So, I guess my question is, which is the better choice, or is it just a matter of opinion, and should I suck it up and use Django if it achieves what I want with minimal fuss (I want authentication and a CRUD interface to my database)? I tried Werkzeug, Glashammer, and friends, but AuthKit and Repoze scared me off, as well as the number of steps involved to just setup basic authentication. I looked at Pylons, but the documentation seems lacking, and when referencing simple features like authentication or a CRUD interface, various wiki pages and documentation seemed to contradict each other, with different hacks for versions and such. </p>
<p><hr /></p>
<p>Thanks to S. Lott for pointing out that I wasn't clear enough. My question is: which of the following is worthwhile in the long run, but not painful in the short (e.g., some sort of middle ground, anyone?) - Learn WSGI, or stick with a "batteries-included" framework? If the latter, I would appreciate a suggestion as to whether I should give Django another try, stick with TurboGears 1.x, or venture into some other framework. </p>
<p>Also, I have tried CherryPy, but couldn't seem to find a good enough CRUD application that I could plop in and use right away.</p>
| 58
|
2009-03-31T17:39:02Z
| 703,375
|
<blockquote>
<p>Learn WSGI</p>
</blockquote>
<p>WSGI is absurdly simple.. It's basically a function that looks like..</p>
<pre><code>def application(environ, start_response) pass
</code></pre>
<p>The function is called when an HTTP request is received. <code>environ</code> contains various data (like the request URI etc etc), <code>start_response</code> is a callable function, used to set headers.</p>
<p>The returned value is the body of the website.</p>
<p>def application(environ, start_response):
start_response("200 OK", [])
return "..."</p>
<p>That's all there is to it, really.. It's not a framework, but more a protocol for web-frameworks to use..</p>
<p>For creating sites, using WSGI is <em>not</em> the "right way" - using existing frameworks is.. but, if you are writing a Python web-framework then using WSGI is absolutely the right way..</p>
<p>Which framework you use (CherryPy, Django, TurboGears etc) is basically personal preference.. Play around in each, see which you like the most, then use it.. There is a StackOverflow question (with a great answer) about this, <a href="http://stackoverflow.com/questions/7170/recommendation-for-straight-forward-python-frameworks">"Recommendation for straight-forward python frameworks"</a></p>
| 4
|
2009-03-31T22:44:35Z
|
[
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] |
Django vs other Python web frameworks?
| 702,179
|
<p>I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with <a href="http://snakelets.sf.net">Snakelets</a> and heartily enjoyed being able to control almost everything at a lower level without much fuss, but then I discovered <a href="http://turbogears.org">TurboGears</a> and I have been using it (1.x) ever since. Tools like Catwalk and the web console are invaluable to me.</p>
<p>But with TurboGears 2 coming out which brings WSGI support, and after reading up on the religious debates between the Django and WSGI camps, I'm really torn between <strong><em>"doing it the right way"</em></strong>, e.g., learning WSGI, spending valuable time writing functionality that already exists in Django and other full-stack frameworks, as opposed to using Django or some high-level framework that does everything for me. The downsides with the latter that I can see are pretty obvious: </p>
<ol>
<li>I'm not learning anything in the process</li>
<li>If I ever need to do anything lower level it's going to be a pain</li>
<li>The overhead required for just a basic site which uses authentication is insane. (IMO)</li>
</ol>
<p>So, I guess my question is, which is the better choice, or is it just a matter of opinion, and should I suck it up and use Django if it achieves what I want with minimal fuss (I want authentication and a CRUD interface to my database)? I tried Werkzeug, Glashammer, and friends, but AuthKit and Repoze scared me off, as well as the number of steps involved to just setup basic authentication. I looked at Pylons, but the documentation seems lacking, and when referencing simple features like authentication or a CRUD interface, various wiki pages and documentation seemed to contradict each other, with different hacks for versions and such. </p>
<p><hr /></p>
<p>Thanks to S. Lott for pointing out that I wasn't clear enough. My question is: which of the following is worthwhile in the long run, but not painful in the short (e.g., some sort of middle ground, anyone?) - Learn WSGI, or stick with a "batteries-included" framework? If the latter, I would appreciate a suggestion as to whether I should give Django another try, stick with TurboGears 1.x, or venture into some other framework. </p>
<p>Also, I have tried CherryPy, but couldn't seem to find a good enough CRUD application that I could plop in and use right away.</p>
| 58
|
2009-03-31T17:39:02Z
| 704,783
|
<p>I'd say the correct answer depends on what you actually want and need, as what will be worthwhile in the long run depends on what you'll need in the long run. If your goal is to get applications deployed ASAP then the 'simpler' route, ie. Django, is surely the way to go. The value of a well-tested and well-documented system that exactly what you want can't be underestimated.</p>
<p>On the other hand if you have time to learn a variety of new things which may apply in other domains and want to have the widest scope for customisation then something like Turbogears is superior. Turbogears gives you maximum flexibility but you <em>will</em> have to spend a lot of time reading external docs for things like Repoze, SQLAlchemy, and Genshi to get anything useful done with it. The TG2 docs are deliberately less detailed than the TG1 docs in some cases because it's considered that the external docs are better than they used to be. Whether this sort of thing is an obstacle or an investment depends on your own requirements.</p>
| 2
|
2009-04-01T09:36:46Z
|
[
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] |
Django vs other Python web frameworks?
| 702,179
|
<p>I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with <a href="http://snakelets.sf.net">Snakelets</a> and heartily enjoyed being able to control almost everything at a lower level without much fuss, but then I discovered <a href="http://turbogears.org">TurboGears</a> and I have been using it (1.x) ever since. Tools like Catwalk and the web console are invaluable to me.</p>
<p>But with TurboGears 2 coming out which brings WSGI support, and after reading up on the religious debates between the Django and WSGI camps, I'm really torn between <strong><em>"doing it the right way"</em></strong>, e.g., learning WSGI, spending valuable time writing functionality that already exists in Django and other full-stack frameworks, as opposed to using Django or some high-level framework that does everything for me. The downsides with the latter that I can see are pretty obvious: </p>
<ol>
<li>I'm not learning anything in the process</li>
<li>If I ever need to do anything lower level it's going to be a pain</li>
<li>The overhead required for just a basic site which uses authentication is insane. (IMO)</li>
</ol>
<p>So, I guess my question is, which is the better choice, or is it just a matter of opinion, and should I suck it up and use Django if it achieves what I want with minimal fuss (I want authentication and a CRUD interface to my database)? I tried Werkzeug, Glashammer, and friends, but AuthKit and Repoze scared me off, as well as the number of steps involved to just setup basic authentication. I looked at Pylons, but the documentation seems lacking, and when referencing simple features like authentication or a CRUD interface, various wiki pages and documentation seemed to contradict each other, with different hacks for versions and such. </p>
<p><hr /></p>
<p>Thanks to S. Lott for pointing out that I wasn't clear enough. My question is: which of the following is worthwhile in the long run, but not painful in the short (e.g., some sort of middle ground, anyone?) - Learn WSGI, or stick with a "batteries-included" framework? If the latter, I would appreciate a suggestion as to whether I should give Django another try, stick with TurboGears 1.x, or venture into some other framework. </p>
<p>Also, I have tried CherryPy, but couldn't seem to find a good enough CRUD application that I could plop in and use right away.</p>
| 58
|
2009-03-31T17:39:02Z
| 926,169
|
<p>Pylons seems a great tool for me:</p>
<ul>
<li>a real web framework (CherryPy is just a web server),</li>
<li>small code base - reuse of other projects,</li>
<li>written entirely with WSGI in mind, based on Paste,</li>
<li>allows you to code the app right away and touch the low level bits if it's necessary,</li>
</ul>
<p>I've used CherryPy and TurboGears and look at many other frameworks but none of them were so light and productive as Pylons is. Check the <a href="http://www.youtube.com/watch?v=Ui-mSFuUZmQ" rel="nofollow">presentation at Google</a>.</p>
| 1
|
2009-05-29T14:09:47Z
|
[
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] |
Django vs other Python web frameworks?
| 702,179
|
<p>I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with <a href="http://snakelets.sf.net">Snakelets</a> and heartily enjoyed being able to control almost everything at a lower level without much fuss, but then I discovered <a href="http://turbogears.org">TurboGears</a> and I have been using it (1.x) ever since. Tools like Catwalk and the web console are invaluable to me.</p>
<p>But with TurboGears 2 coming out which brings WSGI support, and after reading up on the religious debates between the Django and WSGI camps, I'm really torn between <strong><em>"doing it the right way"</em></strong>, e.g., learning WSGI, spending valuable time writing functionality that already exists in Django and other full-stack frameworks, as opposed to using Django or some high-level framework that does everything for me. The downsides with the latter that I can see are pretty obvious: </p>
<ol>
<li>I'm not learning anything in the process</li>
<li>If I ever need to do anything lower level it's going to be a pain</li>
<li>The overhead required for just a basic site which uses authentication is insane. (IMO)</li>
</ol>
<p>So, I guess my question is, which is the better choice, or is it just a matter of opinion, and should I suck it up and use Django if it achieves what I want with minimal fuss (I want authentication and a CRUD interface to my database)? I tried Werkzeug, Glashammer, and friends, but AuthKit and Repoze scared me off, as well as the number of steps involved to just setup basic authentication. I looked at Pylons, but the documentation seems lacking, and when referencing simple features like authentication or a CRUD interface, various wiki pages and documentation seemed to contradict each other, with different hacks for versions and such. </p>
<p><hr /></p>
<p>Thanks to S. Lott for pointing out that I wasn't clear enough. My question is: which of the following is worthwhile in the long run, but not painful in the short (e.g., some sort of middle ground, anyone?) - Learn WSGI, or stick with a "batteries-included" framework? If the latter, I would appreciate a suggestion as to whether I should give Django another try, stick with TurboGears 1.x, or venture into some other framework. </p>
<p>Also, I have tried CherryPy, but couldn't seem to find a good enough CRUD application that I could plop in and use right away.</p>
| 58
|
2009-03-31T17:39:02Z
| 33,663,016
|
<p>Web2py is the secret sauce here. Don't miss checking it out.</p>
| -1
|
2015-11-12T01:36:31Z
|
[
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] |
How to make Django slugify work properly with Unicode strings?
| 702,337
|
<p>What can I do to prevent <code>slugify</code> filter from stripping out non-ASCII alphanumeric characters? (I'm using Django 1.0.2)</p>
<p><a href="http://cnprog.com">cnprog.com</a> has Chinese characters in question URLs, so I looked in their code. They are not using <code>slugify</code> in templates, instead they're calling this method in <code>Question</code> model to get permalinks</p>
<pre><code>def get_absolute_url(self):
return '%s%s' % (reverse('question', args=[self.id]), self.title)
</code></pre>
<p>Are they slugifying the URLs or not?</p>
| 28
|
2009-03-31T18:07:54Z
| 702,445
|
<p>I'm afraid django's definition of slug means ascii, though the django docs don't explicitly state this. This is the source of the defaultfilters for the slugify... you can see that the values are being converted to ascii, with the 'ignore' option in case of errors:</p>
<pre><code>import unicodedata
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
return mark_safe(re.sub('[-\s]+', '-', value))
</code></pre>
<p>Based on that, I'd guess that cnprog.com is not using an official <code>slugify</code> function. You may wish to adapt the django snippet above if you want a different behaviour. </p>
<p>Having said that, though, the RFC for URLs does state that non-us-ascii characters (or, more specifically, anything other than the alphanumerics and $-<em>.+!</em>'()) should be encoded using the %hex notation. If you look at the actual raw GET request that your browser sends (say, using Firebug), you'll see that the chinese characters are in fact encoded before being sent... the browser just makes it look pretty in the display. I suspect this is why slugify insists on ascii only, fwiw.</p>
| 10
|
2009-03-31T18:30:52Z
|
[
"python",
"django",
"unicode",
"django-templates",
"slug"
] |
How to make Django slugify work properly with Unicode strings?
| 702,337
|
<p>What can I do to prevent <code>slugify</code> filter from stripping out non-ASCII alphanumeric characters? (I'm using Django 1.0.2)</p>
<p><a href="http://cnprog.com">cnprog.com</a> has Chinese characters in question URLs, so I looked in their code. They are not using <code>slugify</code> in templates, instead they're calling this method in <code>Question</code> model to get permalinks</p>
<pre><code>def get_absolute_url(self):
return '%s%s' % (reverse('question', args=[self.id]), self.title)
</code></pre>
<p>Are they slugifying the URLs or not?</p>
| 28
|
2009-03-31T18:07:54Z
| 4,019,144
|
<p>Also, the Django version of slugify doesn't use the re.UNICODE flag, so it wouldn't even attempt to understand the meaning of <code>\w\s</code> as it pertains to non-ascii characters.</p>
<p>This custom version is working well for me:</p>
<pre><code>def u_slugify(txt):
"""A custom version of slugify that retains non-ascii characters. The purpose of this
function in the application is to make URLs more readable in a browser, so there are
some added heuristics to retain as much of the title meaning as possible while
excluding characters that are troublesome to read in URLs. For example, question marks
will be seen in the browser URL as %3F and are thereful unreadable. Although non-ascii
characters will also be hex-encoded in the raw URL, most browsers will display them
as human-readable glyphs in the address bar -- those should be kept in the slug."""
txt = txt.strip() # remove trailing whitespace
txt = re.sub('\s*-\s*','-', txt, re.UNICODE) # remove spaces before and after dashes
txt = re.sub('[\s/]', '_', txt, re.UNICODE) # replace remaining spaces with underscores
txt = re.sub('(\d):(\d)', r'\1-\2', txt, re.UNICODE) # replace colons between numbers with dashes
txt = re.sub('"', "'", txt, re.UNICODE) # replace double quotes with single quotes
txt = re.sub(r'[?,:!@#~`+=$%^&\\*()\[\]{}<>]','',txt, re.UNICODE) # remove some characters altogether
return txt
</code></pre>
<p>Note the last regex substitution. This is a workaround to a problem with the more robust expression <code>r'\W'</code>, which seems to either strip out some non-ascii characters or incorrectly re-encode them, as illustrated in the following python interpreter session:</p>
<pre><code>Python 2.5.1 (r251:54863, Jun 17 2009, 20:37:34)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> # Paste in a non-ascii string (simplified Chinese), taken from http://globallives.org/wiki/152/
>>> str = 'æ¨èªèå°å
¨ç社åæèè¶£çä¸åæå½±å¸«å'
>>> str
'\xe6\x82\xa8\xe8\xaa\x8d\xe8\xad\x98\xe5\xb0\x8d\xe5\x85\xa8\xe7\x90\x83\xe7\xa4\xbe\xe5\x8d\x80\xe6\x84\x9f\xe8\x88\x88\xe8\xb6\xa3\xe7\x9a\x84\xe4\xb8\xad\xe5\x9c\x8b\xe6\x94\x9d\xe5\xbd\xb1\xe5\xb8\xab\xe5\x97\x8e'
>>> print str
æ¨èªèå°å
¨ç社åæèè¶£çä¸åæå½±å¸«å
>>> # Substitute all non-word characters with X
>>> re_str = re.sub('\W', 'X', str, re.UNICODE)
>>> re_str
'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\xa3\xe7\x9a\x84\xe4\xb8\xad\xe5\x9c\x8b\xe6\x94\x9d\xe5\xbd\xb1\xe5\xb8\xab\xe5\x97\x8e'
>>> print re_str
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX?çä¸åæå½±å¸«å
>>> # Notice above that it retained the last 7 glyphs, ostensibly because they are word characters
>>> # And where did that question mark come from?
>>>
>>>
>>> # Now do the same with only the last three glyphs of the string
>>> str = '影師å'
>>> print str
影師å
>>> str
'\xe5\xbd\xb1\xe5\xb8\xab\xe5\x97\x8e'
>>> re.sub('\W','X',str,re.U)
'XXXXXXXXX'
>>> re.sub('\W','X',str)
'XXXXXXXXX'
>>> # Huh, now it seems to think those same characters are NOT word characters
</code></pre>
<p>I am unsure what the problem is above, but I'm guessing that it stems from "<a href="http://docs.python.org/library/re.html">whatever is classified as alphanumeric in the Unicode character properties database</a>," and how that is implemented. I have heard that python 3.x has a high priority on better unicode handling, so this may be fixed already. Or, maybe it is correct python behavior, and I am misusing unicode and/or the Chinese language.</p>
<p>For now, a work-around is to avoid character classes, and make substitutions based on explicitly defined character sets. </p>
| 15
|
2010-10-25T21:45:40Z
|
[
"python",
"django",
"unicode",
"django-templates",
"slug"
] |
How to make Django slugify work properly with Unicode strings?
| 702,337
|
<p>What can I do to prevent <code>slugify</code> filter from stripping out non-ASCII alphanumeric characters? (I'm using Django 1.0.2)</p>
<p><a href="http://cnprog.com">cnprog.com</a> has Chinese characters in question URLs, so I looked in their code. They are not using <code>slugify</code> in templates, instead they're calling this method in <code>Question</code> model to get permalinks</p>
<pre><code>def get_absolute_url(self):
return '%s%s' % (reverse('question', args=[self.id]), self.title)
</code></pre>
<p>Are they slugifying the URLs or not?</p>
| 28
|
2009-03-31T18:07:54Z
| 4,036,665
|
<p>There is a python package called <a href="http://pypi.python.org/pypi/Unidecode">unidecode</a> that I've adopted for the askbot Q&A forum, it works well for the latin-based alphabets and even looks reasonable for greek:</p>
<pre><code>>>> import unidecode
>>> from unidecode import unidecode
>>> unidecode(u'διακÏιÏικÏÏ')
'diakritikos'
</code></pre>
<p>It does something weird with asian languages:</p>
<pre><code>>>> unidecode(u'影師å')
'Ying Shi Ma '
>>>
</code></pre>
<p>Does this make sense?</p>
<p>In askbot we compute slugs like so:</p>
<pre><code>from unidecode import unidecode
from django.template import defaultfilters
slug = defaultfilters.slugify(unidecode(input_text))
</code></pre>
| 76
|
2010-10-27T18:58:15Z
|
[
"python",
"django",
"unicode",
"django-templates",
"slug"
] |
How to make Django slugify work properly with Unicode strings?
| 702,337
|
<p>What can I do to prevent <code>slugify</code> filter from stripping out non-ASCII alphanumeric characters? (I'm using Django 1.0.2)</p>
<p><a href="http://cnprog.com">cnprog.com</a> has Chinese characters in question URLs, so I looked in their code. They are not using <code>slugify</code> in templates, instead they're calling this method in <code>Question</code> model to get permalinks</p>
<pre><code>def get_absolute_url(self):
return '%s%s' % (reverse('question', args=[self.id]), self.title)
</code></pre>
<p>Are they slugifying the URLs or not?</p>
| 28
|
2009-03-31T18:07:54Z
| 4,616,724
|
<p>This is what I use:</p>
<p><a href="http://trac.django-fr.org/browser/site/trunk/djangofr/links/slughifi.py" rel="nofollow">http://trac.django-fr.org/browser/site/trunk/djangofr/links/slughifi.py</a></p>
<p>SlugHiFi is a wrapper for regular slugify, with a difference that it replaces national chars with their English alphabet counterparts. </p>
<p>So instead of "Ä" you get "A", instead of "Å" => "L", and so on. </p>
| 4
|
2011-01-06T15:47:21Z
|
[
"python",
"django",
"unicode",
"django-templates",
"slug"
] |
How to make Django slugify work properly with Unicode strings?
| 702,337
|
<p>What can I do to prevent <code>slugify</code> filter from stripping out non-ASCII alphanumeric characters? (I'm using Django 1.0.2)</p>
<p><a href="http://cnprog.com">cnprog.com</a> has Chinese characters in question URLs, so I looked in their code. They are not using <code>slugify</code> in templates, instead they're calling this method in <code>Question</code> model to get permalinks</p>
<pre><code>def get_absolute_url(self):
return '%s%s' % (reverse('question', args=[self.id]), self.title)
</code></pre>
<p>Are they slugifying the URLs or not?</p>
| 28
|
2009-03-31T18:07:54Z
| 6,191,847
|
<p>You might want to look at:
<a href="https://github.com/un33k/django-uuslug">https://github.com/un33k/django-uuslug</a></p>
<p>It will take care of both "U"s for you. <strong>U</strong> in unique and <strong>U</strong> in Unicode.</p>
<p>It will do the job for you hassle free.</p>
| 7
|
2011-05-31T18:26:39Z
|
[
"python",
"django",
"unicode",
"django-templates",
"slug"
] |
How to make Django slugify work properly with Unicode strings?
| 702,337
|
<p>What can I do to prevent <code>slugify</code> filter from stripping out non-ASCII alphanumeric characters? (I'm using Django 1.0.2)</p>
<p><a href="http://cnprog.com">cnprog.com</a> has Chinese characters in question URLs, so I looked in their code. They are not using <code>slugify</code> in templates, instead they're calling this method in <code>Question</code> model to get permalinks</p>
<pre><code>def get_absolute_url(self):
return '%s%s' % (reverse('question', args=[self.id]), self.title)
</code></pre>
<p>Are they slugifying the URLs or not?</p>
| 28
|
2009-03-31T18:07:54Z
| 7,041,953
|
<p>The Mozilla website team has been working on an implementation :
<a href="https://github.com/mozilla/unicode-slugify">https://github.com/mozilla/unicode-slugify</a>
sample code at
<a href="http://davedash.com/2011/03/24/how-we-slug-at-mozilla/">http://davedash.com/2011/03/24/how-we-slug-at-mozilla/</a></p>
| 19
|
2011-08-12T14:55:48Z
|
[
"python",
"django",
"unicode",
"django-templates",
"slug"
] |
How to make Django slugify work properly with Unicode strings?
| 702,337
|
<p>What can I do to prevent <code>slugify</code> filter from stripping out non-ASCII alphanumeric characters? (I'm using Django 1.0.2)</p>
<p><a href="http://cnprog.com">cnprog.com</a> has Chinese characters in question URLs, so I looked in their code. They are not using <code>slugify</code> in templates, instead they're calling this method in <code>Question</code> model to get permalinks</p>
<pre><code>def get_absolute_url(self):
return '%s%s' % (reverse('question', args=[self.id]), self.title)
</code></pre>
<p>Are they slugifying the URLs or not?</p>
| 28
|
2009-03-31T18:07:54Z
| 36,175,658
|
<p>Django 1.9 introduced <code>allow_unicode</code> parameter to <a href="https://docs.djangoproject.com/en/stable/ref/utils/#module-django.utils.text" rel="nofollow"><code>django.utils.text.slugify</code></a>.</p>
<pre><code>>>> slugify("ä½ å¥½ World", allow_unicode=True)
"ä½ å¥½-world"
</code></pre>
<p>If you use Django <= 1.8, you can <a href="https://github.com/django/django/blob/1.9/django/utils/text.py#L413-L427" rel="nofollow">pick up the code from Django 1.9</a>:</p>
<pre><code>import re
import unicodedata
from django.utils import six
from django.utils.encoding import force_text
from django.utils.functional import allow_lazy
from django.utils.safestring import SafeText, mark_safe
def slugify_unicode(value):
value = force_text(value)
value = unicodedata.normalize('NFKC', value)
value = re.sub('[^\w\s-]', '', value, flags=re.U).strip().lower()
return mark_safe(re.sub('[-\s]+', '-', value, flags=re.U))
slugify_unicode = allow_lazy(slugify_unicode, six.text_type, SafeText)
</code></pre>
<p>Which is pretty much <a href="http://stackoverflow.com/a/702445/1529346">the solution suggested by Jarret Hardie</a>.</p>
| 4
|
2016-03-23T10:30:55Z
|
[
"python",
"django",
"unicode",
"django-templates",
"slug"
] |
How to get number of affected rows in sqlalchemy?
| 702,342
|
<p>I have one question concerning Python and the sqlalchemy module. What is the equivalent for <code>cursor.rowcount</code> in the sqlalchemy Python?</p>
| 17
|
2009-03-31T18:08:34Z
| 702,398
|
<p>Although it isn't really stated in the docs, a <code>ResultProxy</code> object does have a <code>rowcount</code> property as well.</p>
| 19
|
2009-03-31T18:21:52Z
|
[
"python",
"sqlalchemy"
] |
Python 3.0.1 Executable Creator
| 702,395
|
<p>Does anyone know if there's a windows Python executable creator program available now that supports Python 3.0.1? It seems that py2exe and pyInstaller, along with all the rest I've found, still aren't anywhere close to supporting 3.0 or 3.0.1.</p>
<p>Any help is greatly appreciated.</p>
<p>Edit: I guess I could downgrade the program to an older version of Python to make it work with py2exe. The hardest part will probably be using an older version of Tkinter.</p>
<p>Has anyone had luck with using py2exe or pyInstaller (or another windows-friendly program) to create an executable that uses Tkinter as well as subprocess.</p>
<p>I'm actually not sure how to get the directory my program will be installed into so subprocess can find the executable program I'm using.</p>
| 6
|
2009-03-31T18:21:20Z
| 703,280
|
<p>Not answering the original question but this:</p>
<blockquote>
<p>I'm actually not sure how to get the directory my program will be installed into so subprocess can find the executable program I'm using.</p>
</blockquote>
<p>You can use something like</p>
<pre><code>if hasattr(sys, 'frozen'): # this means we're installed using py2exe/pyinstaller
INSTDIR = os.path.dirname(sys.executable)
else:
...
</code></pre>
| 5
|
2009-03-31T22:09:51Z
|
[
"python",
"executable",
"py2exe",
"pyinstaller"
] |
Python 3.0.1 Executable Creator
| 702,395
|
<p>Does anyone know if there's a windows Python executable creator program available now that supports Python 3.0.1? It seems that py2exe and pyInstaller, along with all the rest I've found, still aren't anywhere close to supporting 3.0 or 3.0.1.</p>
<p>Any help is greatly appreciated.</p>
<p>Edit: I guess I could downgrade the program to an older version of Python to make it work with py2exe. The hardest part will probably be using an older version of Tkinter.</p>
<p>Has anyone had luck with using py2exe or pyInstaller (or another windows-friendly program) to create an executable that uses Tkinter as well as subprocess.</p>
<p>I'm actually not sure how to get the directory my program will be installed into so subprocess can find the executable program I'm using.</p>
| 6
|
2009-03-31T18:21:20Z
| 1,136,269
|
<p>After searching for many days I came to the conclusion that the isn't currently any method for making executables for python 3.0 scripts.</p>
<p>One workaround I came up with was to use portable python:
<a href="http://www.portablepython.com/releases/" rel="nofollow">http://www.portablepython.com/releases/</a></p>
<p>Which at least allows a separate install which you could distribute with your scripts to help users.</p>
| 1
|
2009-07-16T08:51:46Z
|
[
"python",
"executable",
"py2exe",
"pyinstaller"
] |
Python 3.0.1 Executable Creator
| 702,395
|
<p>Does anyone know if there's a windows Python executable creator program available now that supports Python 3.0.1? It seems that py2exe and pyInstaller, along with all the rest I've found, still aren't anywhere close to supporting 3.0 or 3.0.1.</p>
<p>Any help is greatly appreciated.</p>
<p>Edit: I guess I could downgrade the program to an older version of Python to make it work with py2exe. The hardest part will probably be using an older version of Tkinter.</p>
<p>Has anyone had luck with using py2exe or pyInstaller (or another windows-friendly program) to create an executable that uses Tkinter as well as subprocess.</p>
<p>I'm actually not sure how to get the directory my program will be installed into so subprocess can find the executable program I'm using.</p>
| 6
|
2009-03-31T18:21:20Z
| 1,263,241
|
<p>How about <a href="http://cx-freeze.sourceforge.net/">cx_Freeze</a>. Seems to support python 3.0 and 3.1?</p>
| 11
|
2009-08-11T22:07:12Z
|
[
"python",
"executable",
"py2exe",
"pyinstaller"
] |
Python 3.0.1 Executable Creator
| 702,395
|
<p>Does anyone know if there's a windows Python executable creator program available now that supports Python 3.0.1? It seems that py2exe and pyInstaller, along with all the rest I've found, still aren't anywhere close to supporting 3.0 or 3.0.1.</p>
<p>Any help is greatly appreciated.</p>
<p>Edit: I guess I could downgrade the program to an older version of Python to make it work with py2exe. The hardest part will probably be using an older version of Tkinter.</p>
<p>Has anyone had luck with using py2exe or pyInstaller (or another windows-friendly program) to create an executable that uses Tkinter as well as subprocess.</p>
<p>I'm actually not sure how to get the directory my program will be installed into so subprocess can find the executable program I'm using.</p>
| 6
|
2009-03-31T18:21:20Z
| 1,801,043
|
<p>I got it working with <a href="http://cx-freeze.sourceforge.net/" rel="nofollow">cx_freeze</a>.</p>
<p>Was a bit of a hassle since you have to add a line of code to get around some errors but it turned out to go just fine with Python 3.1.1 and PyQt4.</p>
<p>Also see <a href="http://stackoverflow.com/questions/1737375/building-executables-for-python-3-and-pyqt">here</a> to check on that extra line of code etc.</p>
| 0
|
2009-11-26T01:14:42Z
|
[
"python",
"executable",
"py2exe",
"pyinstaller"
] |
Python 3.0.1 Executable Creator
| 702,395
|
<p>Does anyone know if there's a windows Python executable creator program available now that supports Python 3.0.1? It seems that py2exe and pyInstaller, along with all the rest I've found, still aren't anywhere close to supporting 3.0 or 3.0.1.</p>
<p>Any help is greatly appreciated.</p>
<p>Edit: I guess I could downgrade the program to an older version of Python to make it work with py2exe. The hardest part will probably be using an older version of Tkinter.</p>
<p>Has anyone had luck with using py2exe or pyInstaller (or another windows-friendly program) to create an executable that uses Tkinter as well as subprocess.</p>
<p>I'm actually not sure how to get the directory my program will be installed into so subprocess can find the executable program I'm using.</p>
| 6
|
2009-03-31T18:21:20Z
| 19,952,222
|
<p><s>
Python 3 is not supported by <code>py2exe</code>. The relevant bug to comment on is here:<br>
<a href="https://sourceforge.net/p/py2exe/feature-requests/20/">https://sourceforge.net/p/py2exe/feature-requests/20/</a>
</s></p>
<h1>py2exe for Python3 is out!</h1>
<p>Here is the original bug report:<br>
<a href="http://sourceforge.net/projects/py2exe/">http://sourceforge.net/projects/py2exe/</a></p>
<p>Here is the comment mentioning the release:<br>
<a href="http://sourceforge.net/projects/py2exe/">http://sourceforge.net/projects/py2exe/</a></p>
<p>Here is the package on pypi:<br>
<a href="https://pypi.python.org/pypi/py2exe/0.9.2.0">https://pypi.python.org/pypi/py2exe/0.9.2.0</a></p>
<p><strong>Note that py2exe for Python 3 only supports Python 3.3 and above!</strong></p>
<p><strong>A huge thank you to the py2exe development team!</strong></p>
| 6
|
2013-11-13T11:13:08Z
|
[
"python",
"executable",
"py2exe",
"pyinstaller"
] |
How to limit I/O consumption of Python processes (possibly using ionice)?
| 702,407
|
<p>I would like a particular set of Python subprocesses to be as low-impact as possible. I'm already using <a href="http://www.manpagez.com/man/1/nice/">nice</a> to help limit CPU consumption. But ideally I/O would be limited as well. (If skeptical, please humor me and assume there is value in doing this; it doesn't matter how long they take to run, there can be a lot of them, and there is higher-priority stuff (usually) going on on the same machine, etc.)</p>
<p>One possibility appears to be <code>ionice</code>. Are there any existing Python packages for invoking <code>ionice</code> (Google didn't turn up anything)? It wouldn't be difficult to write code to simply run the <code>ionice</code> command; but I'd prefer to avoid writing code that someone else has written/tested; sometimes there are subtle edge cases, etc. And, is there just a better way to limit I/O consumption?</p>
<p>The <a href="http://linux.die.net/man/1/ionice">man page for ionice</a> suggests that the <code>ionice</code> value can be affected by the <code>nice</code> value, but running this Python 2.6 script appears to disprove that, even for child processes where the <code>nice</code> value is inherited:</p>
<pre><code>#!/usr/bin/env python
import os
import multiprocessing
def print_ionice(name):
print '*** ', name, ' ***'
os.system("echo -n 'nice: '; nice")
os.system("echo -n 'ionice: '; ionice -p%d" % os.getpid())
for niced in (None, 19):
if niced: os.nice(niced)
print '**** niced to: ', niced, ' ****'
print_ionice('parent')
subproc = multiprocessing.Process(target=print_ionice, args=['child'])
subproc.start()
subproc.join()
</code></pre>
<p>Which has the following output:</p>
<pre>
$ uname -as
Linux x.fake.org 2.6.27-11-server #1 SMP Thu Jan 29 20:13:12 UTC 2009 x86_64 GNU/Linux
$ ./foo.py
**** niced to: None ****
*** parent ***
nice: 0
ionice: none: prio 4
*** child ***
nice: 0
ionice: none: prio 4
**** niced to: 19 ****
*** parent ***
nice: 19
ionice: none: prio 4
*** child ***
nice: 19
ionice: none: prio 4
</pre>
| 12
|
2009-03-31T18:23:07Z
| 702,439
|
<p>Why not have whatever <em>launches</em> the processes do the ionice on them (i.e., run them with ionice) rather than having them ionice themselves? It seems a whole lot cleaner.</p>
| 3
|
2009-03-31T18:29:21Z
|
[
"python",
"linux",
"performance",
"unix"
] |
How to limit I/O consumption of Python processes (possibly using ionice)?
| 702,407
|
<p>I would like a particular set of Python subprocesses to be as low-impact as possible. I'm already using <a href="http://www.manpagez.com/man/1/nice/">nice</a> to help limit CPU consumption. But ideally I/O would be limited as well. (If skeptical, please humor me and assume there is value in doing this; it doesn't matter how long they take to run, there can be a lot of them, and there is higher-priority stuff (usually) going on on the same machine, etc.)</p>
<p>One possibility appears to be <code>ionice</code>. Are there any existing Python packages for invoking <code>ionice</code> (Google didn't turn up anything)? It wouldn't be difficult to write code to simply run the <code>ionice</code> command; but I'd prefer to avoid writing code that someone else has written/tested; sometimes there are subtle edge cases, etc. And, is there just a better way to limit I/O consumption?</p>
<p>The <a href="http://linux.die.net/man/1/ionice">man page for ionice</a> suggests that the <code>ionice</code> value can be affected by the <code>nice</code> value, but running this Python 2.6 script appears to disprove that, even for child processes where the <code>nice</code> value is inherited:</p>
<pre><code>#!/usr/bin/env python
import os
import multiprocessing
def print_ionice(name):
print '*** ', name, ' ***'
os.system("echo -n 'nice: '; nice")
os.system("echo -n 'ionice: '; ionice -p%d" % os.getpid())
for niced in (None, 19):
if niced: os.nice(niced)
print '**** niced to: ', niced, ' ****'
print_ionice('parent')
subproc = multiprocessing.Process(target=print_ionice, args=['child'])
subproc.start()
subproc.join()
</code></pre>
<p>Which has the following output:</p>
<pre>
$ uname -as
Linux x.fake.org 2.6.27-11-server #1 SMP Thu Jan 29 20:13:12 UTC 2009 x86_64 GNU/Linux
$ ./foo.py
**** niced to: None ****
*** parent ***
nice: 0
ionice: none: prio 4
*** child ***
nice: 0
ionice: none: prio 4
**** niced to: 19 ****
*** parent ***
nice: 19
ionice: none: prio 4
*** child ***
nice: 19
ionice: none: prio 4
</pre>
| 12
|
2009-03-31T18:23:07Z
| 703,933
|
<p>Hm.</p>
<p>As a start pointer, you should find what <code>syscall</code> number are the <code>ioprio_set</code> and <code>ioprio_get</code> system calls in your kernel. I'd suggest you check in <code>/usr/include/asm/unistd_32.h</code> or <code>/usr/include/asm/unistd_64.h</code>, depending on your kernel arch; if not there, start with the suggestion of the <code>syscall(2)</code> man page, which should be <code>/usr/include/sys/syscall.h</code> and work your way down includes.</p>
<p>Given that, you should use <code>ctypes</code>, Ã la:</p>
<pre><code>def ioprio_set(which, who, ioprio):
rc= ctypes.CDLL('libc.so.6').syscall(289, which, who, ioprio)
# some error checking goes here, and possibly exception throwing
</code></pre>
<p>That's it, more or less. Have fun :)</p>
| 5
|
2009-04-01T03:19:38Z
|
[
"python",
"linux",
"performance",
"unix"
] |
How to limit I/O consumption of Python processes (possibly using ionice)?
| 702,407
|
<p>I would like a particular set of Python subprocesses to be as low-impact as possible. I'm already using <a href="http://www.manpagez.com/man/1/nice/">nice</a> to help limit CPU consumption. But ideally I/O would be limited as well. (If skeptical, please humor me and assume there is value in doing this; it doesn't matter how long they take to run, there can be a lot of them, and there is higher-priority stuff (usually) going on on the same machine, etc.)</p>
<p>One possibility appears to be <code>ionice</code>. Are there any existing Python packages for invoking <code>ionice</code> (Google didn't turn up anything)? It wouldn't be difficult to write code to simply run the <code>ionice</code> command; but I'd prefer to avoid writing code that someone else has written/tested; sometimes there are subtle edge cases, etc. And, is there just a better way to limit I/O consumption?</p>
<p>The <a href="http://linux.die.net/man/1/ionice">man page for ionice</a> suggests that the <code>ionice</code> value can be affected by the <code>nice</code> value, but running this Python 2.6 script appears to disprove that, even for child processes where the <code>nice</code> value is inherited:</p>
<pre><code>#!/usr/bin/env python
import os
import multiprocessing
def print_ionice(name):
print '*** ', name, ' ***'
os.system("echo -n 'nice: '; nice")
os.system("echo -n 'ionice: '; ionice -p%d" % os.getpid())
for niced in (None, 19):
if niced: os.nice(niced)
print '**** niced to: ', niced, ' ****'
print_ionice('parent')
subproc = multiprocessing.Process(target=print_ionice, args=['child'])
subproc.start()
subproc.join()
</code></pre>
<p>Which has the following output:</p>
<pre>
$ uname -as
Linux x.fake.org 2.6.27-11-server #1 SMP Thu Jan 29 20:13:12 UTC 2009 x86_64 GNU/Linux
$ ./foo.py
**** niced to: None ****
*** parent ***
nice: 0
ionice: none: prio 4
*** child ***
nice: 0
ionice: none: prio 4
**** niced to: 19 ****
*** parent ***
nice: 19
ionice: none: prio 4
*** child ***
nice: 19
ionice: none: prio 4
</pre>
| 12
|
2009-03-31T18:23:07Z
| 6,245,160
|
<p><a href="http://code.google.com/p/psutil/" rel="nofollow">psutil</a> exposes this functionality (python 2.4 -> 3.2):</p>
<pre><code>import psutil, os
p = psutil.Process(os.getpid())
p.ionice(psutil.IOPRIO_CLASS_IDLE)
</code></pre>
<p>Also, starting from Python 3.3 this will be available in python stdlib as well:
<a href="http://bugs.python.org/issue10784" rel="nofollow">http://bugs.python.org/issue10784</a></p>
| 13
|
2011-06-05T19:04:18Z
|
[
"python",
"linux",
"performance",
"unix"
] |
User editing own Active Directory data
| 702,493
|
<p>How can I build a web page that allows a logged on user of a Windows 2003 domain change details of his account (probably just First Name, Surname, and Phone number)?</p>
| 0
|
2009-03-31T18:42:43Z
| 703,023
|
<p>Check out <a href="http://code.google.com/p/python-ad/" rel="nofollow">Python-AD</a> (Python Active Directory) which offers the bindings you'll want for communicating with the AD server.</p>
<p>As for the very broad "how can I build a web page" portion of your request, SO has plenty of questions/answers on good web frameworks in python :-)</p>
| 0
|
2009-03-31T20:58:13Z
|
[
"asp.net",
"python",
"active-directory"
] |
User editing own Active Directory data
| 702,493
|
<p>How can I build a web page that allows a logged on user of a Windows 2003 domain change details of his account (probably just First Name, Surname, and Phone number)?</p>
| 0
|
2009-03-31T18:42:43Z
| 703,042
|
<p>Take a look at this <a href="http://www.novell.com/coolsolutions/feature/11204.html" rel="nofollow">http://www.novell.com/coolsolutions/feature/11204.html</a> </p>
| 0
|
2009-03-31T21:03:11Z
|
[
"asp.net",
"python",
"active-directory"
] |
Django admin - inline inlines (or, three model editing at once)
| 702,637
|
<p>I've got a set of models that look like this:</p>
<pre><code>class Page(models.Model):
title = models.CharField(max_length=255)
class LinkSection(models.Model):
page = models.ForeignKey(Page)
title = models.CharField(max_length=255)
class Link(models.Model):
linksection = models.ForeignKey(LinkSection)
text = models.CharField(max_length=255)
url = models.URLField()
</code></pre>
<p>and an admin.py that looks like this:</p>
<pre><code>class LinkInline(admin.TabularInline):
model = Link
class LinkSectionInline(admin.TabularInline):
model = LinkSection
inlines = [ LinkInline, ]
class PageAdmin(admin.ModelAdmin):
inlines = [ LinkSectionInline, ]
</code></pre>
<p>My goal is to get an admin interface that lets me edit everything on one page. The end result of this model structure is that things are generated into a view+template that looks more or less like:</p>
<pre><code><h1>{{page.title}}</h1>
{% for ls in page.linksection_set.objects.all %}
<div>
<h2>{{ls.title}}</h2>
<ul>
{% for l in ls.link_set.objects.all %}
<li><a href="{{l.url}}">{{l.title}}</a></li>
{% endfor %}
</ul>
</div>
{% endfor %}
</code></pre>
<p>I know that the inline-in-an-inline trick fails in the Django admin, as I expected. Does anyone know of a way to allow this kind of three level model editing? Thanks in advance.</p>
| 48
|
2009-03-31T19:20:51Z
| 717,152
|
<p>My recommendation would actually be to change your model. Why not have a <code>ForeignKey</code> in <code>Link</code> to <code>LinkSection</code>? Or, if it's not OneToMany, perhaps a <code>ManyToMany</code> field? The admin interface will generate that for free. Of course, I don't recommend this if links don't logically have anything to do with link sections, but maybe they do? If they don't, please explain what the intended organization is. (For example, is 3 links per section fixed or arbitrary?)</p>
| 1
|
2009-04-04T14:05:51Z
|
[
"python",
"django",
"django-models",
"django-admin",
"inlines"
] |
Django admin - inline inlines (or, three model editing at once)
| 702,637
|
<p>I've got a set of models that look like this:</p>
<pre><code>class Page(models.Model):
title = models.CharField(max_length=255)
class LinkSection(models.Model):
page = models.ForeignKey(Page)
title = models.CharField(max_length=255)
class Link(models.Model):
linksection = models.ForeignKey(LinkSection)
text = models.CharField(max_length=255)
url = models.URLField()
</code></pre>
<p>and an admin.py that looks like this:</p>
<pre><code>class LinkInline(admin.TabularInline):
model = Link
class LinkSectionInline(admin.TabularInline):
model = LinkSection
inlines = [ LinkInline, ]
class PageAdmin(admin.ModelAdmin):
inlines = [ LinkSectionInline, ]
</code></pre>
<p>My goal is to get an admin interface that lets me edit everything on one page. The end result of this model structure is that things are generated into a view+template that looks more or less like:</p>
<pre><code><h1>{{page.title}}</h1>
{% for ls in page.linksection_set.objects.all %}
<div>
<h2>{{ls.title}}</h2>
<ul>
{% for l in ls.link_set.objects.all %}
<li><a href="{{l.url}}">{{l.title}}</a></li>
{% endfor %}
</ul>
</div>
{% endfor %}
</code></pre>
<p>I know that the inline-in-an-inline trick fails in the Django admin, as I expected. Does anyone know of a way to allow this kind of three level model editing? Thanks in advance.</p>
| 48
|
2009-03-31T19:20:51Z
| 1,329,725
|
<p>You can create a new class, similar to TabularInline or StackedInline, that is able to use inline fields itself.</p>
<p>Alternatively, you can create new admin templates, specifically for your model. But that of course overrules the nifty features of the admin interface.</p>
| 0
|
2009-08-25T17:29:16Z
|
[
"python",
"django",
"django-models",
"django-admin",
"inlines"
] |
Django admin - inline inlines (or, three model editing at once)
| 702,637
|
<p>I've got a set of models that look like this:</p>
<pre><code>class Page(models.Model):
title = models.CharField(max_length=255)
class LinkSection(models.Model):
page = models.ForeignKey(Page)
title = models.CharField(max_length=255)
class Link(models.Model):
linksection = models.ForeignKey(LinkSection)
text = models.CharField(max_length=255)
url = models.URLField()
</code></pre>
<p>and an admin.py that looks like this:</p>
<pre><code>class LinkInline(admin.TabularInline):
model = Link
class LinkSectionInline(admin.TabularInline):
model = LinkSection
inlines = [ LinkInline, ]
class PageAdmin(admin.ModelAdmin):
inlines = [ LinkSectionInline, ]
</code></pre>
<p>My goal is to get an admin interface that lets me edit everything on one page. The end result of this model structure is that things are generated into a view+template that looks more or less like:</p>
<pre><code><h1>{{page.title}}</h1>
{% for ls in page.linksection_set.objects.all %}
<div>
<h2>{{ls.title}}</h2>
<ul>
{% for l in ls.link_set.objects.all %}
<li><a href="{{l.url}}">{{l.title}}</a></li>
{% endfor %}
</ul>
</div>
{% endfor %}
</code></pre>
<p>I know that the inline-in-an-inline trick fails in the Django admin, as I expected. Does anyone know of a way to allow this kind of three level model editing? Thanks in advance.</p>
| 48
|
2009-03-31T19:20:51Z
| 1,332,476
|
<p>You need to create a custom <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#form">form</a> and <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#template">template</a> for the <code>LinkSectionInline</code>.</p>
<p>Something like this should work for the form:</p>
<pre><code>LinkFormset = forms.modelformset_factory(Link)
class LinkSectionForm(forms.ModelForm):
def __init__(self, **kwargs):
super(LinkSectionForm, self).__init__(**kwargs)
self.link_formset = LinkFormset(instance=self.instance,
data=self.data or None,
prefix=self.prefix)
def is_valid(self):
return (super(LinkSectionForm, self).is_valid() and
self.link_formset.is_valid())
def save(self, commit=True):
# Supporting commit=False is another can of worms. No use dealing
# it before it's needed. (YAGNI)
assert commit == True
res = super(LinkSectionForm, self).save(commit=commit)
self.link_formset.save()
return res
</code></pre>
<p>(That just came off the top of my head and isn't tested, but it should get you going in the right direction.)</p>
<p>Your template just needs to render the form and form.link_formset appropriately. </p>
| 19
|
2009-08-26T05:18:15Z
|
[
"python",
"django",
"django-models",
"django-admin",
"inlines"
] |
Django admin - inline inlines (or, three model editing at once)
| 702,637
|
<p>I've got a set of models that look like this:</p>
<pre><code>class Page(models.Model):
title = models.CharField(max_length=255)
class LinkSection(models.Model):
page = models.ForeignKey(Page)
title = models.CharField(max_length=255)
class Link(models.Model):
linksection = models.ForeignKey(LinkSection)
text = models.CharField(max_length=255)
url = models.URLField()
</code></pre>
<p>and an admin.py that looks like this:</p>
<pre><code>class LinkInline(admin.TabularInline):
model = Link
class LinkSectionInline(admin.TabularInline):
model = LinkSection
inlines = [ LinkInline, ]
class PageAdmin(admin.ModelAdmin):
inlines = [ LinkSectionInline, ]
</code></pre>
<p>My goal is to get an admin interface that lets me edit everything on one page. The end result of this model structure is that things are generated into a view+template that looks more or less like:</p>
<pre><code><h1>{{page.title}}</h1>
{% for ls in page.linksection_set.objects.all %}
<div>
<h2>{{ls.title}}</h2>
<ul>
{% for l in ls.link_set.objects.all %}
<li><a href="{{l.url}}">{{l.title}}</a></li>
{% endfor %}
</ul>
</div>
{% endfor %}
</code></pre>
<p>I know that the inline-in-an-inline trick fails in the Django admin, as I expected. Does anyone know of a way to allow this kind of three level model editing? Thanks in advance.</p>
| 48
|
2009-03-31T19:20:51Z
| 26,087,864
|
<p><a href="https://pypi.python.org/pypi/django-nested-inlines/0.1" rel="nofollow">Django-nested-inlines</a> is built for just this. Usage is simple.</p>
<pre><code>from django.contrib import admin
from nested_inlines.admin import NestedModelAdmin, NestedStackedInline, NestedTabularInline
from models import A, B, C
class MyNestedInline(NestedTabularInline):
model = C
class MyInline(NestedStackedInline):
model = B
inlines = [MyNestedInline,]
class MyAdmin(NestedModelAdmin):
pass
admin.site.register(A, MyAdmin)
</code></pre>
| 3
|
2014-09-28T18:02:17Z
|
[
"python",
"django",
"django-models",
"django-admin",
"inlines"
] |
How do I generate multi-word terms recursively?
| 702,760
|
<p>Say I have a string of words: <code>'a b c d e f'</code>. I want to generate a list of multi-word terms from this string.</p>
<p>Word order matters. The term <code>'f e d'</code> shouldn't be generated from the above example.</p>
<p><strong>Edit:</strong> Also, words should not be skipped. <code>'a c'</code>, or <code>'b d f'</code> shouldn't be generated.</p>
<p><strong>What I have right now:</strong></p>
<pre><code>doc = 'a b c d e f'
terms= []
one_before = None
two_before = None
for word in doc.split(None):
terms.append(word)
if one_before:
terms.append(' '.join([one_before, word]))
if two_before:
terms.append(' '.join([two_before, one_before, word]))
two_before = one_before
one_before = word
for term in terms:
print term
</code></pre>
<p><strong>Prints:</strong></p>
<pre><code>a
b
a b
c
b c
a b c
d
c d
b c d
e
d e
c d e
f
e f
d e f
</code></pre>
<p>How would I make this a recursive function so that I can pass it a variable maximum number of words per term?</p>
<p><strong>Application:</strong></p>
<p>I'll be using this to generate multi-word terms from readable text in HTML documents. The overall goal is a latent semantic analysis of a large corpus (about two million documents). This is why keeping word order matters (Natural Language Processing and whatnot).</p>
| 5
|
2009-03-31T19:54:20Z
| 702,784
|
<p>I would suggest that you should make your function a generator and then generate required number of terms. You would need to change <code>print</code> to <code>yield</code> (and make the whole block function, obviously).</p>
<p>You might have a look at <a href="http://docs.python.org/library/itertools.html?highlight=itertools#module-itertools" rel="nofollow">itertools</a> module as well, it's fairly useful for kind of work you do.</p>
| 3
|
2009-03-31T20:00:08Z
|
[
"python",
"recursion"
] |
How do I generate multi-word terms recursively?
| 702,760
|
<p>Say I have a string of words: <code>'a b c d e f'</code>. I want to generate a list of multi-word terms from this string.</p>
<p>Word order matters. The term <code>'f e d'</code> shouldn't be generated from the above example.</p>
<p><strong>Edit:</strong> Also, words should not be skipped. <code>'a c'</code>, or <code>'b d f'</code> shouldn't be generated.</p>
<p><strong>What I have right now:</strong></p>
<pre><code>doc = 'a b c d e f'
terms= []
one_before = None
two_before = None
for word in doc.split(None):
terms.append(word)
if one_before:
terms.append(' '.join([one_before, word]))
if two_before:
terms.append(' '.join([two_before, one_before, word]))
two_before = one_before
one_before = word
for term in terms:
print term
</code></pre>
<p><strong>Prints:</strong></p>
<pre><code>a
b
a b
c
b c
a b c
d
c d
b c d
e
d e
c d e
f
e f
d e f
</code></pre>
<p>How would I make this a recursive function so that I can pass it a variable maximum number of words per term?</p>
<p><strong>Application:</strong></p>
<p>I'll be using this to generate multi-word terms from readable text in HTML documents. The overall goal is a latent semantic analysis of a large corpus (about two million documents). This is why keeping word order matters (Natural Language Processing and whatnot).</p>
| 5
|
2009-03-31T19:54:20Z
| 702,788
|
<p>Why are you doing this? You can instead just use a for loop and <a href="http://docs.python.org/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations()</code></a>.</p>
| 3
|
2009-03-31T20:01:14Z
|
[
"python",
"recursion"
] |
How do I generate multi-word terms recursively?
| 702,760
|
<p>Say I have a string of words: <code>'a b c d e f'</code>. I want to generate a list of multi-word terms from this string.</p>
<p>Word order matters. The term <code>'f e d'</code> shouldn't be generated from the above example.</p>
<p><strong>Edit:</strong> Also, words should not be skipped. <code>'a c'</code>, or <code>'b d f'</code> shouldn't be generated.</p>
<p><strong>What I have right now:</strong></p>
<pre><code>doc = 'a b c d e f'
terms= []
one_before = None
two_before = None
for word in doc.split(None):
terms.append(word)
if one_before:
terms.append(' '.join([one_before, word]))
if two_before:
terms.append(' '.join([two_before, one_before, word]))
two_before = one_before
one_before = word
for term in terms:
print term
</code></pre>
<p><strong>Prints:</strong></p>
<pre><code>a
b
a b
c
b c
a b c
d
c d
b c d
e
d e
c d e
f
e f
d e f
</code></pre>
<p>How would I make this a recursive function so that I can pass it a variable maximum number of words per term?</p>
<p><strong>Application:</strong></p>
<p>I'll be using this to generate multi-word terms from readable text in HTML documents. The overall goal is a latent semantic analysis of a large corpus (about two million documents). This is why keeping word order matters (Natural Language Processing and whatnot).</p>
| 5
|
2009-03-31T19:54:20Z
| 702,807
|
<p>This isn't recursive, but I think it does what you want. </p>
<pre><code>doc = 'a b c d e f'
words = doc.split(None)
max = 3
for index in xrange(len(words)):
for n in xrange(max):
if index + n < len(words):
print ' '.join(words[index:index+n+1])
</code></pre>
<p>And here's a recursive solution:</p>
<pre><code>def find_terms(words, max_words_per_term):
if len(words) == 0: return []
return [" ".join(words[:i+1]) for i in xrange(min(len(words), max_words_per_term))] + find_terms(words[1:], max_words_per_term)
doc = 'a b c d e f'
words = doc.split(None)
for term in find_terms(words, 3):
print term
</code></pre>
<p>Here's the recursive function again, with some explaining variables and comments.</p>
<pre><code>def find_terms(words, max_words_per_term):
# If there are no words, you've reached the end. Stop.
if len(words) == 0:
return []
# What's the max term length you could generate from the remaining
# words? It's the lesser of max_words_per_term and how many words
# you have left.
max_term_len = min(len(words), max_words_per_term)
# Find all the terms that start with the first word.
initial_terms = [" ".join(words[:i+1]) for i in xrange(max_term_len)]
# Here's the recursion. Find all of the terms in the list
# of all but the first word.
other_terms = find_terms(words[1:], max_words_per_term)
# Now put the two lists of terms together to get the answer.
return initial_terms + other_terms
</code></pre>
| 11
|
2009-03-31T20:07:02Z
|
[
"python",
"recursion"
] |
How do I generate multi-word terms recursively?
| 702,760
|
<p>Say I have a string of words: <code>'a b c d e f'</code>. I want to generate a list of multi-word terms from this string.</p>
<p>Word order matters. The term <code>'f e d'</code> shouldn't be generated from the above example.</p>
<p><strong>Edit:</strong> Also, words should not be skipped. <code>'a c'</code>, or <code>'b d f'</code> shouldn't be generated.</p>
<p><strong>What I have right now:</strong></p>
<pre><code>doc = 'a b c d e f'
terms= []
one_before = None
two_before = None
for word in doc.split(None):
terms.append(word)
if one_before:
terms.append(' '.join([one_before, word]))
if two_before:
terms.append(' '.join([two_before, one_before, word]))
two_before = one_before
one_before = word
for term in terms:
print term
</code></pre>
<p><strong>Prints:</strong></p>
<pre><code>a
b
a b
c
b c
a b c
d
c d
b c d
e
d e
c d e
f
e f
d e f
</code></pre>
<p>How would I make this a recursive function so that I can pass it a variable maximum number of words per term?</p>
<p><strong>Application:</strong></p>
<p>I'll be using this to generate multi-word terms from readable text in HTML documents. The overall goal is a latent semantic analysis of a large corpus (about two million documents). This is why keeping word order matters (Natural Language Processing and whatnot).</p>
| 5
|
2009-03-31T19:54:20Z
| 1,932,985
|
<p>What you are looking for is N-gram algorithm. That will give you [a,ab,b,bc,c,cd,...].</p>
| 1
|
2009-12-19T13:59:57Z
|
[
"python",
"recursion"
] |
Is there a better trivial Python WebDAV server code snippet than this?
| 702,780
|
<p>Does anyone have a better code snippet for a trivial Python <a href="http://en.wikipedia.org/wiki/WebDAV" rel="nofollow">WebDAV</a> server? The code below (which is cobbled together from some Google search results) appears to work under Python 2.6, but I wonder if someone has something they have used before, a <em>little</em> more tested and complete. I'd prefer a stdlib-only snippet over a third-party package. It is for some test code to hit so does not have to be production-worthy.</p>
<pre><code>import httplib
import BaseHTTPServer
class WebDAV(BaseHTTPServer.BaseHTTPRequestHandler):
"""
Ultra-simplistic WebDAV server.
"""
def do_PUT(self):
path = os.path.normpath(self.path)
if os.path.isabs(path):
path = path[1:] # safe assumption due to normpath above
directory = os.path.dirname(path)
if not os.path.isdir(directory):
os.makedirs(directory)
content_length = int(self.headers['Content-Length'])
with open(path, "w") as f:
f.write(self.rfile.read(content_length))
self.send_response(httplib.OK)
def server_main(server_class=BaseHTTPServer.HTTPServer,
handler_class=WebDAV):
server_class(('', 9231), handler_class).serve_forever()
</code></pre>
| 1
|
2009-03-31T19:58:46Z
| 704,597
|
<p>You can try akaDAV. It is a WebDAV module for Twisted that you can get at <a href="http://akadav.sourceforge.net/" rel="nofollow">http://akadav.sourceforge.net/</a>.</p>
<p>I think it is not maintained anymore but I've got it to work and it supports most operations (except locks).</p>
| 1
|
2009-04-01T08:32:31Z
|
[
"python",
"webdav"
] |
Is there a better trivial Python WebDAV server code snippet than this?
| 702,780
|
<p>Does anyone have a better code snippet for a trivial Python <a href="http://en.wikipedia.org/wiki/WebDAV" rel="nofollow">WebDAV</a> server? The code below (which is cobbled together from some Google search results) appears to work under Python 2.6, but I wonder if someone has something they have used before, a <em>little</em> more tested and complete. I'd prefer a stdlib-only snippet over a third-party package. It is for some test code to hit so does not have to be production-worthy.</p>
<pre><code>import httplib
import BaseHTTPServer
class WebDAV(BaseHTTPServer.BaseHTTPRequestHandler):
"""
Ultra-simplistic WebDAV server.
"""
def do_PUT(self):
path = os.path.normpath(self.path)
if os.path.isabs(path):
path = path[1:] # safe assumption due to normpath above
directory = os.path.dirname(path)
if not os.path.isdir(directory):
os.makedirs(directory)
content_length = int(self.headers['Content-Length'])
with open(path, "w") as f:
f.write(self.rfile.read(content_length))
self.send_response(httplib.OK)
def server_main(server_class=BaseHTTPServer.HTTPServer,
handler_class=WebDAV):
server_class(('', 9231), handler_class).serve_forever()
</code></pre>
| 1
|
2009-03-31T19:58:46Z
| 1,126,409
|
<p>Or try PyFileServer, which I picked up for further develpment by the name WsgiDAV (<a href="http://code.google.com/p/wsgidav/" rel="nofollow">http://code.google.com/p/wsgidav/</a>)<br>
<strong>Edit:</strong> the project has moved to GitHub (<a href="https://github.com/mar10/wsgidav" rel="nofollow">https://github.com/mar10/wsgidav</a>)</p>
| 3
|
2009-07-14T16:05:47Z
|
[
"python",
"webdav"
] |
Is there a better trivial Python WebDAV server code snippet than this?
| 702,780
|
<p>Does anyone have a better code snippet for a trivial Python <a href="http://en.wikipedia.org/wiki/WebDAV" rel="nofollow">WebDAV</a> server? The code below (which is cobbled together from some Google search results) appears to work under Python 2.6, but I wonder if someone has something they have used before, a <em>little</em> more tested and complete. I'd prefer a stdlib-only snippet over a third-party package. It is for some test code to hit so does not have to be production-worthy.</p>
<pre><code>import httplib
import BaseHTTPServer
class WebDAV(BaseHTTPServer.BaseHTTPRequestHandler):
"""
Ultra-simplistic WebDAV server.
"""
def do_PUT(self):
path = os.path.normpath(self.path)
if os.path.isabs(path):
path = path[1:] # safe assumption due to normpath above
directory = os.path.dirname(path)
if not os.path.isdir(directory):
os.makedirs(directory)
content_length = int(self.headers['Content-Length'])
with open(path, "w") as f:
f.write(self.rfile.read(content_length))
self.send_response(httplib.OK)
def server_main(server_class=BaseHTTPServer.HTTPServer,
handler_class=WebDAV):
server_class(('', 9231), handler_class).serve_forever()
</code></pre>
| 1
|
2009-03-31T19:58:46Z
| 3,554,256
|
<p><a href="http://code.google.com/p/wsgidav/" rel="nofollow">WsgiDAV</a></p>
| 1
|
2010-08-24T07:22:30Z
|
[
"python",
"webdav"
] |
Executing Java programs through Python
| 702,861
|
<p>How do I do this?</p>
| 8
|
2009-03-31T20:20:32Z
| 702,888
|
<p>You can execute anything you want from Python with the <a href="http://docs.python.org/library/os.html#os.system"><code>os.system()</code></a> function.</p>
<blockquote>
<p><strong>os.system(command)</strong><br />
Execute the command
(a string) in a subshell. This is
implemented by calling the Standard C
function system, and has the same
limitations. Changes to os.environ,
sys.stdin, etc. are not reflected in
the environment of the executed
command.</p>
</blockquote>
<p>For more power and flexibility you will want to look at the <a href="http://docs.python.org/library/subprocess.html#module-subprocess"><code>subprocess</code></a> module:</p>
<blockquote>
<p>The subprocess module allows you to
spawn new processes, connect to their
input/output/error pipes, and obtain
their return codes.</p>
</blockquote>
| 8
|
2009-03-31T20:25:59Z
|
[
"java",
"python"
] |
Executing Java programs through Python
| 702,861
|
<p>How do I do this?</p>
| 8
|
2009-03-31T20:20:32Z
| 703,221
|
<p>Of course, Jython allows you to use Java classes from within Python. It's an alternate way of looking at it that would allow much tighter integration of the Java code.</p>
| 5
|
2009-03-31T21:52:05Z
|
[
"java",
"python"
] |
URL encode a non-value pair in Python
| 702,986
|
<p>I'm trying to use Google's AJAX (JSON) Web Search API in Python. I'm stuck because Python's urllib.urlencode() only takes value pairs, not strings by themselves, to encode. In Google's API, the query string is the search term and it doesn't associate with a variable.</p>
<pre><code>query = "string that needs to be encoded"
params = urllib.urlencode(query) # THIS FAILS
# http://code.google.com/apis/ajaxsearch/documentation/reference.html
url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&%s&%s" % (params, GOOGLE_API_KEY)
request = urllib2.Request(url)
request.add_header('Referer', GOOGLE_REFERER)
search_results = urllib2.urlopen(request)
raw_results = search_results.read()
json = simplejson.loads(raw_results)
estimatedResultCount = json['responseData']['cursor']['estimatedResultCount']
if estimatedResultCount != 0:
print "Google: %s hits" % estimatedResultCount
</code></pre>
<p>How do I urlencode my search terms?</p>
| 14
|
2009-03-31T20:48:16Z
| 703,002
|
<p>I think you're looking for <a href="http://docs.python.org/library/urllib.html#urllib.quote"><code>urllib.quote</code></a> instead.</p>
| 36
|
2009-03-31T20:52:33Z
|
[
"python",
"json",
"urlencode"
] |
Using email.HeaderParser with imaplib.fetch in python?
| 703,185
|
<p>Does anyone have a good example of using the HeaderParser class in Python for a message that you pull down with imaplib.fetch?</p>
<p>I have been able to find a lot of related things, but nothing that does just this.</p>
<p>Do I need to full down the fetch has an RFC822? I was hoping to simply pull down the subjects.</p>
<p>Thanks!</p>
| 7
|
2009-03-31T21:40:57Z
| 703,479
|
<p>Good news: you're right... you don't need to pull down the RFC822. The <code>message_parts</code> parameter to <code>fetch()</code> lets you be quite fine-grained.</p>
<p>Here's a simple example of how to fetch just the header:</p>
<pre><code>import imaplib
from email.parser import HeaderParser
conn = imaplib.IMAP4('my.host.com')
conn.login('my@username.com', 'mypassword')
conn.select()
conn.search(None, 'ALL') # returns a nice list of messages...
# let's say I pick #1 from this
data = conn.fetch(1, '(BODY[HEADER])')
# gloss over data structure of return... I assume you know these
# gives something like:
# ('OK', [(1 (BODY[HEADER] {1662', 'Received: etc....')])
header_data = data[1][0][1]
parser = HeaderParser()
msg = parser.parsestr(header_data)
<email.message.Message instance at 0x2a>
print msg.keys()
['Received', 'Received', 'Received', 'Cc', 'Message-Id', 'From', 'To',
'In-Reply-To', 'Content-Type', 'Content-Transfer-Encoding', 'Mime-Version',
'Subject', 'Date', 'References', 'X-Mailer',
'X-yoursite-MailScanner-Information',
'X-yoursite-MailScanner', 'X-yoursite-MailScanner-From', 'Return-Path',
'X-OriginalArrivalTime']
</code></pre>
<p>The full list of message parts that can be passed as the second argument to <code>fetch</code> is in the IMAP4 spec: <a href="http://tools.ietf.org/html/rfc1730#section-6.4.5">http://tools.ietf.org/html/rfc1730#section-6.4.5</a></p>
| 16
|
2009-03-31T23:27:07Z
|
[
"python",
"email"
] |
Most efficient way of loading formatted binary files in Python
| 703,262
|
<p>I have binary files no larger than 20Mb in size that have a header section and then a data section containing sequences of uchars. I have Numpy, SciPy, etc. and each library has different ways of loading in the data. Any suggestions for the most efficient methods I should use?</p>
| 5
|
2009-03-31T22:03:36Z
| 703,267
|
<p>Use the <a href="http://docs.python.org/library/struct.html" rel="nofollow">struct</a> module, or possibly a custom module written in C if performance is critical.</p>
| 8
|
2009-03-31T22:05:12Z
|
[
"python",
"input",
"binaryfiles"
] |
Most efficient way of loading formatted binary files in Python
| 703,262
|
<p>I have binary files no larger than 20Mb in size that have a header section and then a data section containing sequences of uchars. I have Numpy, SciPy, etc. and each library has different ways of loading in the data. Any suggestions for the most efficient methods I should use?</p>
| 5
|
2009-03-31T22:03:36Z
| 703,588
|
<p>I found that <code>array.fromfile</code> is the fastest methods for homogeneous data.</p>
| 0
|
2009-04-01T00:27:11Z
|
[
"python",
"input",
"binaryfiles"
] |
Most efficient way of loading formatted binary files in Python
| 703,262
|
<p>I have binary files no larger than 20Mb in size that have a header section and then a data section containing sequences of uchars. I have Numpy, SciPy, etc. and each library has different ways of loading in the data. Any suggestions for the most efficient methods I should use?</p>
| 5
|
2009-03-31T22:03:36Z
| 703,957
|
<p><a href="http://docs.python.org/library/struct.html" rel="nofollow">struct</a> should work for the header section, while numpy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html#numpy.memmap" rel="nofollow">memmap</a> would be efficient for the data section if you are going to manipulate it in numpy anyways. There's no need to stress out about being inconsistent here. Both methods are compatible, just use the right tool for each job.</p>
| 4
|
2009-04-01T03:32:45Z
|
[
"python",
"input",
"binaryfiles"
] |
Most efficient way of loading formatted binary files in Python
| 703,262
|
<p>I have binary files no larger than 20Mb in size that have a header section and then a data section containing sequences of uchars. I have Numpy, SciPy, etc. and each library has different ways of loading in the data. Any suggestions for the most efficient methods I should use?</p>
| 5
|
2009-03-31T22:03:36Z
| 704,265
|
<p><a href="http://www.hl.id.au/projects/bdec/" rel="nofollow">bdec</a> seems promising.</p>
| 1
|
2009-04-01T06:12:57Z
|
[
"python",
"input",
"binaryfiles"
] |
Python: an iteration over a non-empty list with no if-clause comes up empty. Why?
| 703,520
|
<p>How can an iterator over a non-empty sequence, with no filtering and no aggregation (<code>sum()</code>, etc.), yield nothing?</p>
<p>Consider a simple example:</p>
<pre><code>sequence = ['a', 'b', 'c']
list((el, ord(el)) for el in sequence)
</code></pre>
<p>This yields <code>[('a', 97), ('b', 98), ('c', 99)]</code> as expected.</p>
<p>Now, just swap the <code>ord(el)</code> out for an expression that takes the first value out of some generator using <code>(...).next()</code> â forgive the contrived example:</p>
<pre><code>def odd_integers_up_to_length(str):
return (x for x in xrange(len(str)) if x%2==1)
list((el, odd_integers_up_to_length(el).next()) for el in sequence)
</code></pre>
<p>This yields <code>[]</code>. Yeah, empty list. No <code>('a', </code>stuff<code>)</code> tuples. Nothing.</p>
<p>But we're not filtering or aggregating or reducing. A generator expression over <code>n</code> objects without filtering or aggregation must yield <code>n</code> objects, right? What's going on?</p>
| 4
|
2009-03-31T23:53:51Z
| 703,534
|
<p><code>odd_integers_up_to_length(el).next()</code> will raise StopIteration, which isn't caught there, but is caught for the generator expression within it, stopping it without ever yielding anything.</p>
<p>look at the first iteration, when the value is 'a':</p>
<pre><code>>>> odd_integers_up_to_length('a').next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
</code></pre>
| 13
|
2009-03-31T23:59:40Z
|
[
"python",
"iterator",
"generator",
"leaky-abstraction"
] |
Python: an iteration over a non-empty list with no if-clause comes up empty. Why?
| 703,520
|
<p>How can an iterator over a non-empty sequence, with no filtering and no aggregation (<code>sum()</code>, etc.), yield nothing?</p>
<p>Consider a simple example:</p>
<pre><code>sequence = ['a', 'b', 'c']
list((el, ord(el)) for el in sequence)
</code></pre>
<p>This yields <code>[('a', 97), ('b', 98), ('c', 99)]</code> as expected.</p>
<p>Now, just swap the <code>ord(el)</code> out for an expression that takes the first value out of some generator using <code>(...).next()</code> â forgive the contrived example:</p>
<pre><code>def odd_integers_up_to_length(str):
return (x for x in xrange(len(str)) if x%2==1)
list((el, odd_integers_up_to_length(el).next()) for el in sequence)
</code></pre>
<p>This yields <code>[]</code>. Yeah, empty list. No <code>('a', </code>stuff<code>)</code> tuples. Nothing.</p>
<p>But we're not filtering or aggregating or reducing. A generator expression over <code>n</code> objects without filtering or aggregation must yield <code>n</code> objects, right? What's going on?</p>
| 4
|
2009-03-31T23:53:51Z
| 703,539
|
<p>What happens is that the <code>next()</code> call raises a <code>StopIteration</code> exception, which bubbles up the stack to the outer generator expression and stops <em>that</em> iteration.</p>
<p>A <code>StopIteration</code> is the normal way for an iterator to signal that it's done. Generally we don't see it, because generally the <code>next()</code> call occurs within a construct that consumes the iterator, e.g. <code>for x in iterator</code> or <code>sum(iterator)</code>. But when we call <code>next()</code> directly, we are the ones responsible for catching the <code>StopIteration</code>. Not doing so springs a leak in the abstraction, which here leads to unexpected behavior in the outer iteration.</p>
<p>The lesson, I suppose: be careful about direct calls to <code>next()</code>.</p>
| 4
|
2009-04-01T00:01:30Z
|
[
"python",
"iterator",
"generator",
"leaky-abstraction"
] |
Python: an iteration over a non-empty list with no if-clause comes up empty. Why?
| 703,520
|
<p>How can an iterator over a non-empty sequence, with no filtering and no aggregation (<code>sum()</code>, etc.), yield nothing?</p>
<p>Consider a simple example:</p>
<pre><code>sequence = ['a', 'b', 'c']
list((el, ord(el)) for el in sequence)
</code></pre>
<p>This yields <code>[('a', 97), ('b', 98), ('c', 99)]</code> as expected.</p>
<p>Now, just swap the <code>ord(el)</code> out for an expression that takes the first value out of some generator using <code>(...).next()</code> â forgive the contrived example:</p>
<pre><code>def odd_integers_up_to_length(str):
return (x for x in xrange(len(str)) if x%2==1)
list((el, odd_integers_up_to_length(el).next()) for el in sequence)
</code></pre>
<p>This yields <code>[]</code>. Yeah, empty list. No <code>('a', </code>stuff<code>)</code> tuples. Nothing.</p>
<p>But we're not filtering or aggregating or reducing. A generator expression over <code>n</code> objects without filtering or aggregation must yield <code>n</code> objects, right? What's going on?</p>
| 4
|
2009-03-31T23:53:51Z
| 703,543
|
<p>str is a reserved keword, you should name your variable differently</p>
<p>I was also to advise about the next</p>
| 0
|
2009-04-01T00:03:10Z
|
[
"python",
"iterator",
"generator",
"leaky-abstraction"
] |
Python: an iteration over a non-empty list with no if-clause comes up empty. Why?
| 703,520
|
<p>How can an iterator over a non-empty sequence, with no filtering and no aggregation (<code>sum()</code>, etc.), yield nothing?</p>
<p>Consider a simple example:</p>
<pre><code>sequence = ['a', 'b', 'c']
list((el, ord(el)) for el in sequence)
</code></pre>
<p>This yields <code>[('a', 97), ('b', 98), ('c', 99)]</code> as expected.</p>
<p>Now, just swap the <code>ord(el)</code> out for an expression that takes the first value out of some generator using <code>(...).next()</code> â forgive the contrived example:</p>
<pre><code>def odd_integers_up_to_length(str):
return (x for x in xrange(len(str)) if x%2==1)
list((el, odd_integers_up_to_length(el).next()) for el in sequence)
</code></pre>
<p>This yields <code>[]</code>. Yeah, empty list. No <code>('a', </code>stuff<code>)</code> tuples. Nothing.</p>
<p>But we're not filtering or aggregating or reducing. A generator expression over <code>n</code> objects without filtering or aggregation must yield <code>n</code> objects, right? What's going on?</p>
| 4
|
2009-03-31T23:53:51Z
| 703,545
|
<pre><code>>>> seq=['a','b','c']
>>> list((el,4) for el in seq)
[('a',4), ('b',4), ('c',4)]
</code></pre>
<p>So it's not <code>list</code> giving you trouble here...</p>
| 0
|
2009-04-01T00:04:53Z
|
[
"python",
"iterator",
"generator",
"leaky-abstraction"
] |
Anything like SciPy in Ruby?
| 703,717
|
<p>Looking further into the differences between Python and Ruby, is there a Ruby equivalent to SciPy, or what other scientific math gems are available for Ruby?</p>
| 14
|
2009-04-01T01:33:31Z
| 703,731
|
<p>There's nothing quite as mature or well done as SciPy, but check out <a href="http://sciruby.com/">SciRuby</a> and <a href="http://narray.rubyforge.org/">Numerical Ruby</a>.</p>
| 17
|
2009-04-01T01:39:34Z
|
[
"python",
"ruby",
"math",
"scipy"
] |
Anything like SciPy in Ruby?
| 703,717
|
<p>Looking further into the differences between Python and Ruby, is there a Ruby equivalent to SciPy, or what other scientific math gems are available for Ruby?</p>
| 14
|
2009-04-01T01:33:31Z
| 703,736
|
<p>rnum</p>
<blockquote>
<p>Ruby Numerical Library is a linear
algebra package using Blas and Lapack.</p>
</blockquote>
<p><a href="http://rnum.rubyforge.org/" rel="nofollow">http://rnum.rubyforge.org/</a></p>
<p>Site has some speed comparisons</p>
| 2
|
2009-04-01T01:42:19Z
|
[
"python",
"ruby",
"math",
"scipy"
] |
Anything like SciPy in Ruby?
| 703,717
|
<p>Looking further into the differences between Python and Ruby, is there a Ruby equivalent to SciPy, or what other scientific math gems are available for Ruby?</p>
| 14
|
2009-04-01T01:33:31Z
| 8,365,878
|
<p>linalg <a href="https://github.com/wedesoft" rel="nofollow">https://github.com/wedesoft</a>, installation instructions: <a href="http://www.quora.com/Installation-Instructions/How-do-I-install-Ruby-linalg-library-on-Mac" rel="nofollow">http://www.quora.com/Installation-Instructions/How-do-I-install-Ruby-linalg-library-on-Mac</a></p>
| 0
|
2011-12-03T05:55:15Z
|
[
"python",
"ruby",
"math",
"scipy"
] |
Anything like SciPy in Ruby?
| 703,717
|
<p>Looking further into the differences between Python and Ruby, is there a Ruby equivalent to SciPy, or what other scientific math gems are available for Ruby?</p>
| 14
|
2009-04-01T01:33:31Z
| 10,339,519
|
<p>Someone else mentioned NArray and Ara T. Howard's / @drawohara's SciRuby.</p>
<p>But there's also a new <a href="http://sciruby.com" rel="nofollow">SciRuby project</a> (proceeding with Ara's and Masahiro Tanaka's blessings) which includes a dense and sparse matrix gem, <a href="http://github.com/SciRuby/nmatrix" rel="nofollow">NMatrix</a>. It's not finished yet, but it does basic stuff.</p>
<p>The <a href="http://github.com/SciRuby" rel="nofollow">SciRuby github account</a> also has a bunch of other useful gems, including statsample (for statistics) and rubyvis (for visualization).</p>
| 1
|
2012-04-26T18:46:07Z
|
[
"python",
"ruby",
"math",
"scipy"
] |
How would I compute exactly 30 days into the past with Python (down to the minute)?
| 703,907
|
<p>In Python, I'm attempting to retrieve the date/time that is exactly 30 days (30*24hrs) into the past. At present, I'm simply doing:</p>
<pre><code>>>> import datetime
>>> start_date = datetime.date.today() + datetime.timedelta(-30)
</code></pre>
<p>Which returns a datetime object, but with no time data:</p>
<pre><code>>>> start_date.year
2009
>>> start_date.hour
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'datetime.date' object has no attribute 'hour'
</code></pre>
| 16
|
2009-04-01T02:59:46Z
| 703,912
|
<p>You want to use a <code>datetime</code> object instead of just a <code>date</code> object:</p>
<pre><code>start_date = datetime.datetime.now() + datetime.timedelta(-30)
</code></pre>
<p><code>date</code> just stores a date and <code>time</code> just a time. <code>datetime</code> is a date with a time.</p>
| 37
|
2009-04-01T03:01:48Z
|
[
"python",
"datetime",
"date",
"time"
] |
How would I compute exactly 30 days into the past with Python (down to the minute)?
| 703,907
|
<p>In Python, I'm attempting to retrieve the date/time that is exactly 30 days (30*24hrs) into the past. At present, I'm simply doing:</p>
<pre><code>>>> import datetime
>>> start_date = datetime.date.today() + datetime.timedelta(-30)
</code></pre>
<p>Which returns a datetime object, but with no time data:</p>
<pre><code>>>> start_date.year
2009
>>> start_date.hour
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'datetime.date' object has no attribute 'hour'
</code></pre>
| 16
|
2009-04-01T02:59:46Z
| 703,916
|
<p>date <> datetime</p>
| -5
|
2009-04-01T03:05:31Z
|
[
"python",
"datetime",
"date",
"time"
] |
Using pydev with Eclipse on OSX
| 703,925
|
<p>I setup PyDev with this path for the python interpreter
/System/Library/Frameworks/Python.framework/Versions/2.5/Python
since the one under /usr/bin were alias and Eclipse won't select it. I can run my python script now but cannot run the shell as an external tool. The message I get is</p>
<p>variable references empty selection ${resource_loc}</p>
<p>Same if I use {container_loc}</p>
<p>Any thoughts ?</p>
<p>Sunit</p>
| 11
|
2009-04-01T03:11:00Z
| 704,037
|
<p>I believe <code>${resource_loc}</code> or <code>${container_loc}</code> (without any argument) are based on the current selection in your workbench when you are launching your script.</p>
<p>So are you selecting the right resource when selecting that script through the "external tool" runner ?<br />
At least, click on the project name before you run one of the external programs.<br />
Note: it works with a selection in the <a href="http://dev.eclipse.org/newslists/news.eclipse.platform/msg50264.html" rel="nofollow">Navigator or Package Explorers views</a> (the latest might not be available in PyDev environment though)</p>
| 0
|
2009-04-01T04:14:21Z
|
[
"python",
"eclipse"
] |
Using pydev with Eclipse on OSX
| 703,925
|
<p>I setup PyDev with this path for the python interpreter
/System/Library/Frameworks/Python.framework/Versions/2.5/Python
since the one under /usr/bin were alias and Eclipse won't select it. I can run my python script now but cannot run the shell as an external tool. The message I get is</p>
<p>variable references empty selection ${resource_loc}</p>
<p>Same if I use {container_loc}</p>
<p>Any thoughts ?</p>
<p>Sunit</p>
| 11
|
2009-04-01T03:11:00Z
| 884,296
|
<p>Common practice seems to be to install an up-to-date Python 2.5 from python.org and use that instead of the system installation. I saw that recommended here and there when I got started on Mac OS X.</p>
<p>It installs under <code>/Library</code> (as opposed to <code>/System/Library</code>) so the system Python is intact. Pydev has /Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python as its configured Python interpreter and all is well.</p>
<p>Can't state for sure that your trouble is due only to using the system's Python installation; in any case this way I have no trouble. Also, this way when you fiddle with your development environment (install things in site-packages, upgrade Python), anything that uses the system Python is sure to be unaffected.</p>
| 3
|
2009-05-19T18:21:03Z
|
[
"python",
"eclipse"
] |
Using pydev with Eclipse on OSX
| 703,925
|
<p>I setup PyDev with this path for the python interpreter
/System/Library/Frameworks/Python.framework/Versions/2.5/Python
since the one under /usr/bin were alias and Eclipse won't select it. I can run my python script now but cannot run the shell as an external tool. The message I get is</p>
<p>variable references empty selection ${resource_loc}</p>
<p>Same if I use {container_loc}</p>
<p>Any thoughts ?</p>
<p>Sunit</p>
| 11
|
2009-04-01T03:11:00Z
| 2,785,302
|
<p>I installed the Python.org version as well, this is a must.</p>
<p>I finally got PyDev working in Eclipse by pointing the interpreter to:</p>
<pre><code>/Library/Frameworks/Python.framework/Versions/2.6/bin/python
</code></pre>
<p>manually. If you don't do it manually (by using the Autoconfig) it seems to not find the right version.</p>
| 10
|
2010-05-06T23:53:40Z
|
[
"python",
"eclipse"
] |
Using pydev with Eclipse on OSX
| 703,925
|
<p>I setup PyDev with this path for the python interpreter
/System/Library/Frameworks/Python.framework/Versions/2.5/Python
since the one under /usr/bin were alias and Eclipse won't select it. I can run my python script now but cannot run the shell as an external tool. The message I get is</p>
<p>variable references empty selection ${resource_loc}</p>
<p>Same if I use {container_loc}</p>
<p>Any thoughts ?</p>
<p>Sunit</p>
| 11
|
2009-04-01T03:11:00Z
| 10,695,484
|
<p>I know this is a ancient post... but, in case of some newbee like me to get the better answer.</p>
<p>I just using "Eclipse Marketplace" from the "Help" menu and search for keyword "python" or "PyDev" to get PyDev, and get it successfully installed.</p>
<p>AND, you should add PyDev to the top-right dock.</p>
<p>For the instance, my eclipse on my laptop's OSX is (Version: Indigo Service Release 2 Build id: 20120216-1857).</p>
<p>Have fun, folks! :)</p>
| 1
|
2012-05-22T03:48:38Z
|
[
"python",
"eclipse"
] |
Can I transpose a file in Vim?
| 704,130
|
<p>I know I can use AWK but I am on a Windows box. I am making a function for others that may not have AWK. I also know I can write a C program but I would love not have to create maintain and compile something for a little Vim utility I am making. </p>
<p>The original file might be</p>
<pre><code>THE DAY WAS LONG
THE WAY WAS FAST
</code></pre>
<p>and it would become</p>
<pre><code>TT
HH
EE
DW
AA
YY
WW
AA
SS
LF
OA
NS
GT
</code></pre>
<p>UPDATE: Golf rules apply to selecting correct answer.</p>
<p>UPDATE: Python fans should check out Mr. Duffy's answer below.</p>
| 12
|
2009-04-01T05:09:10Z
| 704,139
|
<p>Vim support for a number of scripting languages built in -- see <A HREF="http://www.vim.org/htmldoc/if_pyth.html" rel="nofollow">the Python interface</A> as an example.</p>
<p>Just modify <code>vim.current.buffer</code> appropriately and you're set.</p>
<p>To be a little more specific:</p>
<pre><code>function! Rotate()
python <<EOF
import vim, itertools
max_len = max((len(n) for n in vim.current.buffer))
vim.current.buffer[:] = [
''.join(n) for n in itertools.izip(
*( n + ' ' * (max_len - len(n))
for n in vim.current.buffer))]
EOF
endfunction
</code></pre>
| 10
|
2009-04-01T05:13:33Z
|
[
"python",
"vim",
"text-files",
"text-parsing"
] |
Can I transpose a file in Vim?
| 704,130
|
<p>I know I can use AWK but I am on a Windows box. I am making a function for others that may not have AWK. I also know I can write a C program but I would love not have to create maintain and compile something for a little Vim utility I am making. </p>
<p>The original file might be</p>
<pre><code>THE DAY WAS LONG
THE WAY WAS FAST
</code></pre>
<p>and it would become</p>
<pre><code>TT
HH
EE
DW
AA
YY
WW
AA
SS
LF
OA
NS
GT
</code></pre>
<p>UPDATE: Golf rules apply to selecting correct answer.</p>
<p>UPDATE: Python fans should check out Mr. Duffy's answer below.</p>
| 12
|
2009-04-01T05:09:10Z
| 704,797
|
<p>Here is a command in Vim language. So you don't have to compile Vim with +python support.</p>
<pre><code>function! s:transpose()
let maxcol = 0
let lines = getline(1, line('$'))
for line in lines
let len = len(line)
if len > maxcol
let maxcol = len
endif
endfor
let newlines = []
for col in range(0, maxcol - 1)
let newline = ''
for line in lines
let line_with_extra_spaces = printf('%-'.maxcol.'s', line)
let newline .= line_with_extra_spaces[col]
endfor
call add(newlines, newline)
endfor
1,$"_d
call setline(1, newlines)
endfunction
command! TransposeBuffer call s:transpose()
</code></pre>
<p>Put this in newly created .vim file inside vim/plugin dir or put this to your [._]vimrc.<br>
Execute <code>:TransposeBuffer</code> to transpose current buffer </p>
| 11
|
2009-04-01T09:42:24Z
|
[
"python",
"vim",
"text-files",
"text-parsing"
] |
Can I transpose a file in Vim?
| 704,130
|
<p>I know I can use AWK but I am on a Windows box. I am making a function for others that may not have AWK. I also know I can write a C program but I would love not have to create maintain and compile something for a little Vim utility I am making. </p>
<p>The original file might be</p>
<pre><code>THE DAY WAS LONG
THE WAY WAS FAST
</code></pre>
<p>and it would become</p>
<pre><code>TT
HH
EE
DW
AA
YY
WW
AA
SS
LF
OA
NS
GT
</code></pre>
<p>UPDATE: Golf rules apply to selecting correct answer.</p>
<p>UPDATE: Python fans should check out Mr. Duffy's answer below.</p>
| 12
|
2009-04-01T05:09:10Z
| 704,857
|
<p>If scripts don't do it for you, you could record the actions to a register (the carriage returns are added for readability):</p>
<pre><code>qa
1G0
xGo<Esc>p
1G0j
xGp
q
</code></pre>
<p>This will give you a macro that you could run against the example above, or any 2-line strings of the same length. You only need to know the length of the string so you can iterate the operation the correct number of time</p>
<pre><code>16@a
</code></pre>
<p>A fairly basic solution, but it works.</p>
| 5
|
2009-04-01T10:01:20Z
|
[
"python",
"vim",
"text-files",
"text-parsing"
] |
Can I transpose a file in Vim?
| 704,130
|
<p>I know I can use AWK but I am on a Windows box. I am making a function for others that may not have AWK. I also know I can write a C program but I would love not have to create maintain and compile something for a little Vim utility I am making. </p>
<p>The original file might be</p>
<pre><code>THE DAY WAS LONG
THE WAY WAS FAST
</code></pre>
<p>and it would become</p>
<pre><code>TT
HH
EE
DW
AA
YY
WW
AA
SS
LF
OA
NS
GT
</code></pre>
<p>UPDATE: Golf rules apply to selecting correct answer.</p>
<p>UPDATE: Python fans should check out Mr. Duffy's answer below.</p>
| 12
|
2009-04-01T05:09:10Z
| 7,318,088
|
<p><a href="http://stackoverflow.com/questions/704130/can-i-transpose-a-file-in-vim#704139">Charles Duffy's code</a> could be shortened/improved using <code>izip_longest</code> instead of <code>izip</code>:</p>
<pre><code>function! Rotate()
:py import vim, itertools
:py vim.current.buffer[:] = [''.join(c) for c in itertools.izip_longest(*vim.current.buffer, fillvalue=" ")]
endfunction
</code></pre>
| 0
|
2011-09-06T09:58:16Z
|
[
"python",
"vim",
"text-files",
"text-parsing"
] |
Can I transpose a file in Vim?
| 704,130
|
<p>I know I can use AWK but I am on a Windows box. I am making a function for others that may not have AWK. I also know I can write a C program but I would love not have to create maintain and compile something for a little Vim utility I am making. </p>
<p>The original file might be</p>
<pre><code>THE DAY WAS LONG
THE WAY WAS FAST
</code></pre>
<p>and it would become</p>
<pre><code>TT
HH
EE
DW
AA
YY
WW
AA
SS
LF
OA
NS
GT
</code></pre>
<p>UPDATE: Golf rules apply to selecting correct answer.</p>
<p>UPDATE: Python fans should check out Mr. Duffy's answer below.</p>
| 12
|
2009-04-01T05:09:10Z
| 7,320,629
|
<p>The following function performs required editing operations to "transpose" the
contents of the current buffer.</p>
<pre><code>fu!T()
let[m,n,@s]=[0,line('$'),"lDG:pu\r``j@s"]
g/^/let m=max([m,col('$')])
exe'%norm!'.m."A \e".m.'|D'
sil1norm!@s
exe'%norm!'.n.'gJ'
endf
</code></pre>
<p>Below is its one-line version,</p>
<pre><code>let[m,n,@s]=[0,line('$'),"lDG:pu\r``j@s"]|exe'g/^/let m=max([m,col("$")])'|exe'%norm!'.m."A \e".m.'|D'|exe'sil1norm!@s'|exe'%norm!'.n.'gJ'
</code></pre>
| 1
|
2011-09-06T13:23:13Z
|
[
"python",
"vim",
"text-files",
"text-parsing"
] |
Can I transpose a file in Vim?
| 704,130
|
<p>I know I can use AWK but I am on a Windows box. I am making a function for others that may not have AWK. I also know I can write a C program but I would love not have to create maintain and compile something for a little Vim utility I am making. </p>
<p>The original file might be</p>
<pre><code>THE DAY WAS LONG
THE WAY WAS FAST
</code></pre>
<p>and it would become</p>
<pre><code>TT
HH
EE
DW
AA
YY
WW
AA
SS
LF
OA
NS
GT
</code></pre>
<p>UPDATE: Golf rules apply to selecting correct answer.</p>
<p>UPDATE: Python fans should check out Mr. Duffy's answer below.</p>
| 12
|
2009-04-01T05:09:10Z
| 10,470,420
|
<p>I've developed a vim plugin to do it. You can find it <a href="https://github.com/salsifis/vim-transpose" rel="nofollow">here</a>. Run <code>:Transpose</code> to transpose the whole file.</p>
| 0
|
2012-05-06T12:18:38Z
|
[
"python",
"vim",
"text-files",
"text-parsing"
] |
How can I convert a character to a integer in Python, and viceversa?
| 704,152
|
<p>I want to get, given a character, its <code>ASCII</code> value.</p>
<p>For example, for the character <code>a</code>, I want to get <code>97</code>, and vice versa.</p>
| 160
|
2009-04-01T05:19:15Z
| 704,157
|
<p>ord and chr</p>
| 4
|
2009-04-01T05:21:22Z
|
[
"python",
"integer",
"char",
"type-conversion"
] |
How can I convert a character to a integer in Python, and viceversa?
| 704,152
|
<p>I want to get, given a character, its <code>ASCII</code> value.</p>
<p>For example, for the character <code>a</code>, I want to get <code>97</code>, and vice versa.</p>
| 160
|
2009-04-01T05:19:15Z
| 704,158
|
<pre><code>>>> ord('a')
97
>>> chr(97)
'a'
</code></pre>
| 20
|
2009-04-01T05:21:39Z
|
[
"python",
"integer",
"char",
"type-conversion"
] |
How can I convert a character to a integer in Python, and viceversa?
| 704,152
|
<p>I want to get, given a character, its <code>ASCII</code> value.</p>
<p>For example, for the character <code>a</code>, I want to get <code>97</code>, and vice versa.</p>
| 160
|
2009-04-01T05:19:15Z
| 704,160
|
<p>Use <a href="http://docs.python.org/library/functions.html#chr"><code>chr()</code></a> and <a href="http://docs.python.org/library/functions.html#ord"><code>ord()</code></a>:</p>
<pre><code>>>> chr(97)
'a'
>>> ord('a')
97
</code></pre>
| 300
|
2009-04-01T05:22:00Z
|
[
"python",
"integer",
"char",
"type-conversion"
] |
How can I convert a character to a integer in Python, and viceversa?
| 704,152
|
<p>I want to get, given a character, its <code>ASCII</code> value.</p>
<p>For example, for the character <code>a</code>, I want to get <code>97</code>, and vice versa.</p>
| 160
|
2009-04-01T05:19:15Z
| 704,183
|
<p>The question has been answered but I think this reference is a good thing to keep note of. <a href="http://docs.python.org/library/functions.html">http://docs.python.org/library/functions.html</a></p>
| 7
|
2009-04-01T05:36:09Z
|
[
"python",
"integer",
"char",
"type-conversion"
] |
How do I schedule a process' termination?
| 704,203
|
<p>I need to run a process, wait a few hours, kill it, and start it again. Is there an easy way that I can accomplish this with Python or Bash? I can run it in the background but how do I identify it to use kill on it?</p>
| 0
|
2009-04-01T05:44:36Z
| 704,223
|
<p>One idea: Save the process's PID (returned by <code>fork()</code> in your child process) to a file, then either schedule a <code>cron</code> job to kill it or kill it manually, reading the PID from the file.</p>
<p>Another option: Create a shell script wrapper that automatically kills and restarts the process. Same as above, but you can keep the PID in memory, sleep for as long as you need, kill the process, then loop.</p>
| 0
|
2009-04-01T05:52:05Z
|
[
"python",
"bash",
"unix",
"process",
"kill"
] |
How do I schedule a process' termination?
| 704,203
|
<p>I need to run a process, wait a few hours, kill it, and start it again. Is there an easy way that I can accomplish this with Python or Bash? I can run it in the background but how do I identify it to use kill on it?</p>
| 0
|
2009-04-01T05:44:36Z
| 704,224
|
<p>Take a look at the <a href="http://olympus.het.brown.edu/cgi-bin/man/man2html?start-stop-daemon" rel="nofollow">start-stop-daemon</a> utility. </p>
| 0
|
2009-04-01T05:52:52Z
|
[
"python",
"bash",
"unix",
"process",
"kill"
] |
How do I schedule a process' termination?
| 704,203
|
<p>I need to run a process, wait a few hours, kill it, and start it again. Is there an easy way that I can accomplish this with Python or Bash? I can run it in the background but how do I identify it to use kill on it?</p>
| 0
|
2009-04-01T05:44:36Z
| 704,226
|
<p>You could always write a script to search for those processes and kill them if found.
Then add a cronjob to execute the script.</p>
<p><a href="http://www.faqs.org/faqs/unix-faq/faq/part3/section-10.html" rel="nofollow">Find process ID of a process with known name</a></p>
<p><a href="http://www.unix.com/unix-dummies-questions-answers/5245-script-kill-all-child-process-given-pid.html" rel="nofollow">Kill processes with a known ID</a></p>
<p>In python <a href="http://docs.python.org/library/os.html#os.kill" rel="nofollow">os.kill()</a> can be used to kill a process given the id.</p>
| 0
|
2009-04-01T05:53:16Z
|
[
"python",
"bash",
"unix",
"process",
"kill"
] |
How do I schedule a process' termination?
| 704,203
|
<p>I need to run a process, wait a few hours, kill it, and start it again. Is there an easy way that I can accomplish this with Python or Bash? I can run it in the background but how do I identify it to use kill on it?</p>
| 0
|
2009-04-01T05:44:36Z
| 704,229
|
<p>This is in Perl, but you should be able to translate it to Python.</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
#set times to 0 for infinite times
my ($times, $wait, $program, @args) = @ARGV;
$times = -1 unless $times;
while ($times--) {
$times = -1 if $times < 0; #catch -2 and turn it back into -1
die "could not fork" unless defined(my $pid = fork);
#replace child with the program we want to launch
unless ($pid) {
exec $program, @args;
}
#parent waits and kills the child if it isn't done yet
sleep $wait;
kill $pid;
waitpid $pid, 0; #clean up child
}
</code></pre>
<p>Because I am trying to teach myself Python, here it is in Python (I do not trust this code):</p>
<pre><code>#!/usr/bin/python
import os
import sys
import time
times = int(sys.argv[1])
wait = int(sys.argv[2])
program = sys.argv[3]
args = []
if len(sys.argv) >= 4:
args = sys.argv[3:]
if times == 0:
times = -1
while times:
times = times - 1
if times < 0:
times = -1
pid = os.fork()
if not pid:
os.execvp(program, args)
time.sleep(wait)
os.kill(pid, 15)
os.waitpid(pid, 0)
</code></pre>
| 3
|
2009-04-01T05:55:10Z
|
[
"python",
"bash",
"unix",
"process",
"kill"
] |
How do I schedule a process' termination?
| 704,203
|
<p>I need to run a process, wait a few hours, kill it, and start it again. Is there an easy way that I can accomplish this with Python or Bash? I can run it in the background but how do I identify it to use kill on it?</p>
| 0
|
2009-04-01T05:44:36Z
| 704,273
|
<p>With bash:</p>
<pre><code>while true ; do
run_proc &
PID=$!
sleep 3600
kill $PID
sleep 30
done
</code></pre>
<p>The <code>$!</code> bash variable expands to the PID of the most recently started background process. The <code>sleep</code> just waits an hour, then the <code>kill</code> shuts down that process.</p>
<p>The <code>while</code> loop just keeps doing it over and over.</p>
| 3
|
2009-04-01T06:16:21Z
|
[
"python",
"bash",
"unix",
"process",
"kill"
] |
How do I schedule a process' termination?
| 704,203
|
<p>I need to run a process, wait a few hours, kill it, and start it again. Is there an easy way that I can accomplish this with Python or Bash? I can run it in the background but how do I identify it to use kill on it?</p>
| 0
|
2009-04-01T05:44:36Z
| 704,889
|
<p>In python:</p>
<pre><code>import subprocess
import time
while True:
p = subprocess.Popen(['/path/to/program', 'param1', 'param2'])
time.sleep(2 * 60 * 60) # wait time in seconds - 2 hours
p.kill()
</code></pre>
<p><code>p.kill()</code> is python >= 2.6.</p>
<p>On python <= 2.5 you can use this instead:</p>
<pre><code>os.kill(p.pid, signal.SIGTERM)
</code></pre>
| 2
|
2009-04-01T10:12:16Z
|
[
"python",
"bash",
"unix",
"process",
"kill"
] |
How do I schedule a process' termination?
| 704,203
|
<p>I need to run a process, wait a few hours, kill it, and start it again. Is there an easy way that I can accomplish this with Python or Bash? I can run it in the background but how do I identify it to use kill on it?</p>
| 0
|
2009-04-01T05:44:36Z
| 713,898
|
<p>Not an ideal method but if you know the name of the program and you know it's the only process of that name running on the system you can use this in cron:</p>
<pre><code>0 */2 * * * kill `ps -ax | grep programName | grep -v grep | awk '{ print $1 }'` && ./scriptToStartProcess
</code></pre>
<p>This will run every two hours on the hour and kill programName then start the process again.</p>
| 0
|
2009-04-03T13:26:36Z
|
[
"python",
"bash",
"unix",
"process",
"kill"
] |
python: finding a missing letter in the alphabet from a list - least lines of code
| 704,526
|
<p>I'm trying to find the missing letter in the alphabet from the list with the least lines of code.</p>
<p>If the list is sorted already (using list.sort()), what is the fastest or least lines of code to find the missing letter.</p>
<p>If I know there are only one missing letter.</p>
<p>(This is not any type of interview questions. I actually need to do this in my script where I want to put least amount of work in this process since it will be repeated over and over indeterministically)</p>
| 2
|
2009-04-01T08:08:19Z
| 704,554
|
<p>Here's one way of doing it, assuming your "alphabets" is integers, and that the list has at least two items:</p>
<pre><code>for i in xrange(1, len(a)):
if a[i] != a[i - 1] + 1:
print a[i - 1] + 1, "is missing"
</code></pre>
| 0
|
2009-04-01T08:20:13Z
|
[
"python"
] |
python: finding a missing letter in the alphabet from a list - least lines of code
| 704,526
|
<p>I'm trying to find the missing letter in the alphabet from the list with the least lines of code.</p>
<p>If the list is sorted already (using list.sort()), what is the fastest or least lines of code to find the missing letter.</p>
<p>If I know there are only one missing letter.</p>
<p>(This is not any type of interview questions. I actually need to do this in my script where I want to put least amount of work in this process since it will be repeated over and over indeterministically)</p>
| 2
|
2009-04-01T08:08:19Z
| 704,562
|
<p>With sorted lists a binary search is usually the fastest alghorythm. Could you please provide an example list and an example "missing alphabet"?</p>
| 0
|
2009-04-01T08:21:18Z
|
[
"python"
] |
python: finding a missing letter in the alphabet from a list - least lines of code
| 704,526
|
<p>I'm trying to find the missing letter in the alphabet from the list with the least lines of code.</p>
<p>If the list is sorted already (using list.sort()), what is the fastest or least lines of code to find the missing letter.</p>
<p>If I know there are only one missing letter.</p>
<p>(This is not any type of interview questions. I actually need to do this in my script where I want to put least amount of work in this process since it will be repeated over and over indeterministically)</p>
| 2
|
2009-04-01T08:08:19Z
| 704,576
|
<p>Some questions:</p>
<ul>
<li>Are all the letters upper or lower case? (a/A)</li>
<li>Is this the only alphabet you'll want to check?</li>
<li>Why are you doing this so often?</li>
</ul>
<p>Least lines of code:</p>
<pre><code># do this once, outside the loop
alphabet=set(string.ascii_lowercase)
# inside the loop, just 1 line:
missingletter=(alphabet-set(yourlist)).pop()
</code></pre>
<p>The advantage of the above is that you can do it without having to sort the list first. If, however, the list is <em>always</em> sorted, you can use bisection to get there faster. On a simple 26-letter alphabet though, is there much point?</p>
<p>Bisection (done in ~4 lookups):</p>
<pre><code>frompos, topos = 0, len(str)
for i in range(1,100): #never say forever with bisection...
trypos = (frompos+topos+1)/2
print "try:",frompos,trypos,topos
if alphabet[trypos] != str[trypos]:
topos = trypos
else:
frompos = trypos
if topos-frompos==1:
if alphabet[topos] != str[topos]:
print alphabet[frompos]
else:
print alphabet[topos]
break
</code></pre>
<p>This code requires fewer lookups, so is by far the better scaling version O(log n), but may still be slower when executed via a python interpreter because it goes via python <code>if</code>s instead of <code>set</code> operations written in C.</p>
<p>(Thanks to J.F.Sebastian and Kylotan for their comments)</p>
| 10
|
2009-04-01T08:25:40Z
|
[
"python"
] |
python: finding a missing letter in the alphabet from a list - least lines of code
| 704,526
|
<p>I'm trying to find the missing letter in the alphabet from the list with the least lines of code.</p>
<p>If the list is sorted already (using list.sort()), what is the fastest or least lines of code to find the missing letter.</p>
<p>If I know there are only one missing letter.</p>
<p>(This is not any type of interview questions. I actually need to do this in my script where I want to put least amount of work in this process since it will be repeated over and over indeterministically)</p>
| 2
|
2009-04-01T08:08:19Z
| 704,595
|
<p>Using a list comprehension:</p>
<pre><code>>>> import string
>>> sourcelist = 'abcdefghijklmnopqrstuvwx'
>>> [letter for letter in string.ascii_lowercase if letter not in sourcelist]
['y', 'z']
>>>
</code></pre>
<p>The <a href="http://docs.python.org/library/string.html" rel="nofollow">string</a> module has some predefined constants that are useful.</p>
<pre><code>>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>> string.octdigits
'01234567'
>>> string.digits
'0123456789'
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>>
</code></pre>
| 7
|
2009-04-01T08:32:13Z
|
[
"python"
] |
python: finding a missing letter in the alphabet from a list - least lines of code
| 704,526
|
<p>I'm trying to find the missing letter in the alphabet from the list with the least lines of code.</p>
<p>If the list is sorted already (using list.sort()), what is the fastest or least lines of code to find the missing letter.</p>
<p>If I know there are only one missing letter.</p>
<p>(This is not any type of interview questions. I actually need to do this in my script where I want to put least amount of work in this process since it will be repeated over and over indeterministically)</p>
| 2
|
2009-04-01T08:08:19Z
| 704,601
|
<p>if you're talking about alphabet as letters:</p>
<pre><code>letterSet = set()
for word in wordList:
letterSet.update(set(word.lower()))
import string
alphabet = set(string.lowercase)
missingLetters = alphabet.difference(letterSet)
</code></pre>
| 0
|
2009-04-01T08:33:25Z
|
[
"python"
] |
python: finding a missing letter in the alphabet from a list - least lines of code
| 704,526
|
<p>I'm trying to find the missing letter in the alphabet from the list with the least lines of code.</p>
<p>If the list is sorted already (using list.sort()), what is the fastest or least lines of code to find the missing letter.</p>
<p>If I know there are only one missing letter.</p>
<p>(This is not any type of interview questions. I actually need to do this in my script where I want to put least amount of work in this process since it will be repeated over and over indeterministically)</p>
| 2
|
2009-04-01T08:08:19Z
| 704,686
|
<p>In the too clever for it's own good category, and assuming there is exactly one missing letter in a lowercase alphabet:</p>
<pre><code>print chr(2847 - sum(map(ord, theString)))
</code></pre>
<p><strong>[Edit]</strong>
I've run some timings on the various solutions to see which is faster.
Mine turned out to be fairly slow in practice (slightly faster if I use itertools.imap instead).</p>
<p>Surprisingly, the <a href="http://stackoverflow.com/questions/704526/python-finding-a-missing-letter-in-the-alphabet-from-a-list-least-lines-of-cod/704595#704595">listcomp solution</a> by monkut turned out to be fastest - I'd have expected the set solutions to do better, as this must scan the list each time to find the missing letter.
I tried first converting the test list to a set in advance of membership checking, expecting this to speed it up but in fact it made it slower. It looks like the constant factor delay in creating the set dwarfs the cost of using an O(n**2) algorithm for such a short string.</p>
<p>That suggested than an even more basic approach, taking advantage of early exiting, could perform even better. The below is what I think currently performs best:</p>
<pre><code>def missing_letter_basic(s):
for letter in string.ascii_lowercase:
if letter not in s: return letter
raise Exception("No missing letter")
</code></pre>
<p>The bisection method is probably best when working with larger strings however. It is only just edged out by the listcomp here, and has much better asymptotic complexity, so for strings larger than an alphabet, it will clearly win. </p>
<p><strong>[Edit2]</strong></p>
<p>Actually, cheating a bit, I can get even better than that, abusing the fact that there are only 26 strings to check, behold the ultimate O(1) missing letter finder! </p>
<pre><code>find_missing_letter = dict((string.ascii_lowercase[:i]+string.ascii_lowercase[i+1:],
string.ascii_lowercase[i]) for i in range(26)).get
>>> find_missing_letter('abcdefghijklmnoprstuvwxyz')
'q'
</code></pre>
<p>Here are my timings (500000 runs, tested with letters missing near the start, middle and end of the string (b, m and y)</p>
<pre><code> "b" "m" "y"
bisect : 2.762 2.872 2.922 (Phil H)
find_gap : 3.388 4.533 5.642 (unwind)
listcomp : 2.832 2.858 2.822 (monkut)
listcomp_set : 4.770 4.746 4.700 As above, with sourcelist=set(sourcelist) first
set_difference : 2.924 2.945 2.880 (Phil H)
sum : 3.815 3.806 3.868
sum_imap : 3.284 3.280 3.260
basic : 0.544 1.379 2.359
dict_lookup : 0.135 0.133 0.134
</code></pre>
| 7
|
2009-04-01T09:06:28Z
|
[
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.