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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Cherrypy server unavailable from anything but localhost | 1,555,319 | <p>I am having an issue with cherrypy that looks solved, but doesn't work. I can only bind on localhost or 127.0.0.1. Windows XP Home and Mac OS X (linux untested), cherrypy 3.1.2, python 2.5.4. This is the end of my app:</p>
<pre><code>global_conf = {
'global': { 'server.environment= "production"'
'engine.autoreload_on : True'
'engine.autoreload_frequency = 5 '
'server.socket_host': '0.0.0.0',
'server.socket_port': 8080}
}
cherrypy.config.update(global_conf)
cherrypy.tree.mount(home, '/', config = application_conf)
cherrypy.engine.start()
</code></pre>
| 2 | 2009-10-12T15:46:01Z | 1,601,743 | <p>If you're using a dual-stack OS, it may be that localhost is resolving to ::1 (the IPv6 localhost) and not 127.0.0.1 (the IPv4 localhost). Try accessing the server using <a href="http://127.0.0.1:8080" rel="nofollow">http://127.0.0.1:8080</a>.</p>
<p>Also, if you're using an dual-stack capable OS, you can set server.socket_host to '::', and it will listen on all addresses in IPv6 and IPv4.</p>
| 3 | 2009-10-21T15:44:15Z | [
"python",
"cherrypy"
] |
appengine remote api unable to login | 1,555,469 | <p>When I go to appengine.google.com/a/mydomain.com i am able to login and
see all my apps and administer them.</p>
<p>However, when I try to use the remote_api the same username/password does not work.</p>
<p>I'm using the interactive console code from <a href="http://code.google.com/appengine/articles/remote%5Fapi.html" rel="nofollow">http://code.google.com/appengine/articles/remote%5Fapi.html</a> </p>
| 3 | 2009-10-12T16:13:20Z | 1,555,950 | <p>I've come across the same issue while developing for GAE on google apps. To make it work, I've created a simple wrapper around a snippet provided by Nick (blog.notdot.net - I can't seem to find the proper reference right now) that has been working for me. You can find it <a href="http://github.com/caio/bizarrice/blob/master/remote%5Fconsole.py" rel="nofollow">here</a>.</p>
| 0 | 2009-10-12T17:43:33Z | [
"python",
"google-app-engine"
] |
appengine remote api unable to login | 1,555,469 | <p>When I go to appengine.google.com/a/mydomain.com i am able to login and
see all my apps and administer them.</p>
<p>However, when I try to use the remote_api the same username/password does not work.</p>
<p>I'm using the interactive console code from <a href="http://code.google.com/appengine/articles/remote%5Fapi.html" rel="nofollow">http://code.google.com/appengine/articles/remote%5Fapi.html</a> </p>
| 3 | 2009-10-12T16:13:20Z | 1,642,695 | <p>This is a known issue with Google Accounts authentication. If you created an app and set it to use Google Accounts for authentication, and you yourself use a Google Apps account, you will not be able to authenticate against your app as an administrator using that account, even if you've created a Google Account for that email address. The workaround for now is to create a gmail account and add it as an administrator of your app, using that whenever you need to authenticate against your app as an administrator. You can still use your existing account for deployments and to log in to the admin console.</p>
<p>It's a pain, I know - I run into it every day myself.</p>
| 6 | 2009-10-29T10:14:21Z | [
"python",
"google-app-engine"
] |
sending a non-blocking HTTP POST request | 1,555,517 | <p>I have a two websites in php and python.
When a user sends a request to the server I need php/python to send an HTTP POST request to a remote server. I want to reply to the user immediately without waiting for a response from the remote server.</p>
<p>Is it possible to continue running a php/python script after sending a response to the user. In that case I'll first reply to the user and only then send the HTTP POST request to the remote server.</p>
<p>Is it possible to create a non-blocking HTTP client in php/python without handling the response at all?</p>
<p>A solution that will have the same logic in php and python is preferable for me.</p>
<p>Thanks </p>
| 10 | 2009-10-12T16:22:37Z | 1,555,614 | <p>What you need to do is have the PHP script execute another script that does the server call and then sends the user the request.</p>
| 1 | 2009-10-12T16:35:50Z | [
"php",
"python",
"nonblocking"
] |
sending a non-blocking HTTP POST request | 1,555,517 | <p>I have a two websites in php and python.
When a user sends a request to the server I need php/python to send an HTTP POST request to a remote server. I want to reply to the user immediately without waiting for a response from the remote server.</p>
<p>Is it possible to continue running a php/python script after sending a response to the user. In that case I'll first reply to the user and only then send the HTTP POST request to the remote server.</p>
<p>Is it possible to create a non-blocking HTTP client in php/python without handling the response at all?</p>
<p>A solution that will have the same logic in php and python is preferable for me.</p>
<p>Thanks </p>
| 10 | 2009-10-12T16:22:37Z | 1,555,641 | <p>You can spawn another process to handle the POST to the other server. In PHP you would spawn the process and "disconnect" so you don't wait for the response.</p>
<pre><code>exec("nohup /path/to/script/post_content.php > /dev/null 2>&1 &");
</code></pre>
<p>You can then you curl to perform the post. If you want to pass parameters to the PHP script, you can use the getopt() function to read them. Not sure if you would do something similar in Python.</p>
| 2 | 2009-10-12T16:41:14Z | [
"php",
"python",
"nonblocking"
] |
sending a non-blocking HTTP POST request | 1,555,517 | <p>I have a two websites in php and python.
When a user sends a request to the server I need php/python to send an HTTP POST request to a remote server. I want to reply to the user immediately without waiting for a response from the remote server.</p>
<p>Is it possible to continue running a php/python script after sending a response to the user. In that case I'll first reply to the user and only then send the HTTP POST request to the remote server.</p>
<p>Is it possible to create a non-blocking HTTP client in php/python without handling the response at all?</p>
<p>A solution that will have the same logic in php and python is preferable for me.</p>
<p>Thanks </p>
| 10 | 2009-10-12T16:22:37Z | 1,555,709 | <p>In PHP you can close the connection by sending this request (this is HTTP related and works also in python, although I don't know the proper syntax to use):</p>
<pre><code>// Send the response to the client
header('Connection: Close');
// Do the background job: just don't output anything!
</code></pre>
<p>Addendum: I forgot to mention you probably have to set the "Context-Length". Also, check out <a href="http://www.php.net/manual/en/features.connection-handling.php#71172" rel="nofollow">this comment</a> for tips and a real test case.</p>
<h3>Example:</h3>
<pre><code><?php
ob_end_clean();
header('Connection: close');
ob_start();
echo 'Your stuff goes here...';
header('Content-Length: ' . ob_get_length());
ob_end_flush();
flush();
// Now we are in background mode
sleep(10);
echo 'This text should not be visible';
?>
</code></pre>
| 7 | 2009-10-12T16:55:03Z | [
"php",
"python",
"nonblocking"
] |
sending a non-blocking HTTP POST request | 1,555,517 | <p>I have a two websites in php and python.
When a user sends a request to the server I need php/python to send an HTTP POST request to a remote server. I want to reply to the user immediately without waiting for a response from the remote server.</p>
<p>Is it possible to continue running a php/python script after sending a response to the user. In that case I'll first reply to the user and only then send the HTTP POST request to the remote server.</p>
<p>Is it possible to create a non-blocking HTTP client in php/python without handling the response at all?</p>
<p>A solution that will have the same logic in php and python is preferable for me.</p>
<p>Thanks </p>
| 10 | 2009-10-12T16:22:37Z | 1,555,718 | <p><a href="http://github.com/progrium/hookah" rel="nofollow">Hookah</a> is designed to solve your problem.</p>
| -3 | 2009-10-12T16:57:46Z | [
"php",
"python",
"nonblocking"
] |
sending a non-blocking HTTP POST request | 1,555,517 | <p>I have a two websites in php and python.
When a user sends a request to the server I need php/python to send an HTTP POST request to a remote server. I want to reply to the user immediately without waiting for a response from the remote server.</p>
<p>Is it possible to continue running a php/python script after sending a response to the user. In that case I'll first reply to the user and only then send the HTTP POST request to the remote server.</p>
<p>Is it possible to create a non-blocking HTTP client in php/python without handling the response at all?</p>
<p>A solution that will have the same logic in php and python is preferable for me.</p>
<p>Thanks </p>
| 10 | 2009-10-12T16:22:37Z | 1,555,721 | <p>in python you could simply close the output stream, then continue to do your post request</p>
<pre><code>sys.stdout.close()
</code></pre>
| 0 | 2009-10-12T16:58:46Z | [
"php",
"python",
"nonblocking"
] |
sending a non-blocking HTTP POST request | 1,555,517 | <p>I have a two websites in php and python.
When a user sends a request to the server I need php/python to send an HTTP POST request to a remote server. I want to reply to the user immediately without waiting for a response from the remote server.</p>
<p>Is it possible to continue running a php/python script after sending a response to the user. In that case I'll first reply to the user and only then send the HTTP POST request to the remote server.</p>
<p>Is it possible to create a non-blocking HTTP client in php/python without handling the response at all?</p>
<p>A solution that will have the same logic in php and python is preferable for me.</p>
<p>Thanks </p>
| 10 | 2009-10-12T16:22:37Z | 23,913,884 | <p>You have to use fsockopen. And don't listen to the result</p>
<pre><code><?php
$fp = fsockopen('example.com', 80);
$vars = array(
'hello' => 'world'
);
$content = http_build_query($vars);
fwrite($fp, "POST /reposter.php HTTP/1.1\r\n");
fwrite($fp, "Host: example.com\r\n");
fwrite($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
fwrite($fp, "Content-Length: ".strlen($content)."\r\n");
fwrite($fp, "Connection: close\r\n");
fwrite($fp, "\r\n");
fwrite($fp, $content);
</code></pre>
| 0 | 2014-05-28T14:04:35Z | [
"php",
"python",
"nonblocking"
] |
Can one prevent Genshi from parsing HTML entities? | 1,555,644 | <p>I have the following Python code using Genshi (simplified):</p>
<pre><code>with open(pathToHTMLFile, 'r') as f:
template = MarkupTemplate(f.read())
finalPage = template.generate().render('html', doctype = 'html')
</code></pre>
<p>The source HTML file contains entities such as <code>&copy;</code>, <code>&trade;</code> and <code>&reg;</code>. Genshi replaces these with their UTF-8 character, which causes problems with the viewer (the output is used as a stand-alone file, not a response to a web request) that eventually sees the resulting HTML. Is there any way to prevent Genshi from parsing these entities? The more common ones like <code>&amp;</code> are passed through just fine.</p>
| 3 | 2009-10-12T16:42:34Z | 1,555,869 | <p>Actually <code>&amp;</code> isn't passed through, it's parsed into an ampersand character, and then serialised back to <code>&amp;</code> on the way out because that's necessary to represent a literal ampersand in HTML. <code>&copy;</code>, on the other hand, is not a necessary escape, so it can be left as its literal character.</p>
<p>So no, there's no way to <em>stop</em> the entity reference being parsed. But you can ensure that non-ASCII characters are re-escaped on the way back out by serialising to plain ASCII:</p>
<pre><code>template.generate().render('html', doctype= 'html', encoding= 'us-ascii')
</code></pre>
<p>You still won't get the entity reference <code>&copy;</code> in your output, but you will get the character reference <code>&#169;</code> which is equivalent and should hopefully be understood by whatever is displaying the final file.</p>
| 9 | 2009-10-12T17:25:43Z | [
"python",
"html",
"entities",
"genshi"
] |
Can one prevent Genshi from parsing HTML entities? | 1,555,644 | <p>I have the following Python code using Genshi (simplified):</p>
<pre><code>with open(pathToHTMLFile, 'r') as f:
template = MarkupTemplate(f.read())
finalPage = template.generate().render('html', doctype = 'html')
</code></pre>
<p>The source HTML file contains entities such as <code>&copy;</code>, <code>&trade;</code> and <code>&reg;</code>. Genshi replaces these with their UTF-8 character, which causes problems with the viewer (the output is used as a stand-alone file, not a response to a web request) that eventually sees the resulting HTML. Is there any way to prevent Genshi from parsing these entities? The more common ones like <code>&amp;</code> are passed through just fine.</p>
| 3 | 2009-10-12T16:42:34Z | 2,650,325 | <p>Sticking </p>
<pre><code><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</code></pre>
<p>in the <code><head></code> of your HTML should cause browsers to correctly render UTF-8.</p>
<p>To clarify, the root issue is that the corresponding © UTF-8 character does not render correctly in static HTML. Placing the meta tag in the HTML tells the browser how to correctly interpret the character set and thus renders the UTF-8 characters correctly.</p>
| 3 | 2010-04-16T03:02:04Z | [
"python",
"html",
"entities",
"genshi"
] |
Can one prevent Genshi from parsing HTML entities? | 1,555,644 | <p>I have the following Python code using Genshi (simplified):</p>
<pre><code>with open(pathToHTMLFile, 'r') as f:
template = MarkupTemplate(f.read())
finalPage = template.generate().render('html', doctype = 'html')
</code></pre>
<p>The source HTML file contains entities such as <code>&copy;</code>, <code>&trade;</code> and <code>&reg;</code>. Genshi replaces these with their UTF-8 character, which causes problems with the viewer (the output is used as a stand-alone file, not a response to a web request) that eventually sees the resulting HTML. Is there any way to prevent Genshi from parsing these entities? The more common ones like <code>&amp;</code> are passed through just fine.</p>
| 3 | 2009-10-12T16:42:34Z | 20,451,838 | <p>To prevent escaping of (x)html markup characters in Genshi:</p>
<pre><code>from genshi.core import Markup
...
newstring = Markup(oldstring)
...
<now apply templates as before, but substituting newstring for oldstring>
</code></pre>
| 0 | 2013-12-08T09:29:48Z | [
"python",
"html",
"entities",
"genshi"
] |
How to dereference a memory location from python ctypes? | 1,555,944 | <p>I want to replicate the following c code in python ctypes:</p>
<pre><code>main() {
long *ptr = (long *)0x7fff96000000;
printf("%lx",*ptr);
}
</code></pre>
<p>I can figure out how to call this memory location as a function pointer but not just do a normal dereference:</p>
<pre><code>from ctypes import *
"""
>>> fptr = CFUNCTYPE(None, None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/ctypes/__init__.py", line 104, in CFUNCTYPE
class CFunctionType(_CFuncPtr):
TypeError: Error when calling the metaclass bases
item 1 in _argtypes_ has no from_param method
"""
fptr = CFUNCTYPE(None, c_void_p) #add c_void_p since you have to have an arg
fptr2 = fptr(0x7fff96000000)
fptr2(c_void_p(0))
#python: segfault at 7fff96000000 ip 00007fff96000000
</code></pre>
<p>Since there it is a segfault with the instruction pointer pointing to this memory location it is successfully calling it. However I can't get it to just read the memory location:</p>
<pre><code>ptr = POINTER(c_long)
ptr2 = ptr(c_long(0x7fff96000000))
#>>> ptr2[0]
#140735709970432
#>>> hex(ptr2[0])
#'0x7fff96000000'
#>>> ptr2.contents
#c_long(140735709970432)
</code></pre>
| 6 | 2009-10-12T17:42:06Z | 1,556,482 | <p><code>ctypes.cast</code>.</p>
<pre><code>>>> import ctypes
>>> c_long_p = ctypes.POINTER(ctypes.c_long)
>>> some_long = ctypes.c_long(42)
>>> ctypes.addressof(some_long)
4300833936
>>> ctypes.cast(4300833936, c_long_p)
<__main__.LP_c_long object at 0x1005983b0>
>>> ctypes.cast(4300833936, c_long_p).contents
c_long(42)
</code></pre>
| 10 | 2009-10-12T19:43:44Z | [
"python",
"ctypes",
"ffi"
] |
Efficient way to find the largest key in a dictionary with non-zero value | 1,555,968 | <p>I'm new Python and trying to implement code in a more Pythonic and efficient fashion.
Given a dictionary with numeric keys and values, what is the best way to find the largest key with a non-zero value?</p>
<p>Thanks</p>
| 5 | 2009-10-12T17:48:22Z | 1,555,991 | <p>Something like this should be reasonably fast:</p>
<pre><code>>>> x = {0: 5, 1: 7, 2: 0}
>>> max(k for k, v in x.iteritems() if v != 0)
1
</code></pre>
<p>(removing the <code>!= 0</code> will be slightly faster still, but obscures the meaning somewhat.)</p>
| 12 | 2009-10-12T17:51:55Z | [
"python",
"dictionary"
] |
Efficient way to find the largest key in a dictionary with non-zero value | 1,555,968 | <p>I'm new Python and trying to implement code in a more Pythonic and efficient fashion.
Given a dictionary with numeric keys and values, what is the best way to find the largest key with a non-zero value?</p>
<p>Thanks</p>
| 5 | 2009-10-12T17:48:22Z | 1,555,997 | <p>Python's max function takes a <code>key=</code> parameter for a "measure" function.</p>
<pre><code>data = {1: 25, 0: 75}
def keymeasure(key):
return data[key] and key
print max(data, key=keymeasure)
</code></pre>
<p>Using an inline lambda to the same effect and same binding of local variables:</p>
<pre><code>print max(data, key=(lambda k: data[k] and k))
</code></pre>
<p>last alternative to bind in the local var into the anonymous key function</p>
<pre><code>print max(data, key=(lambda k, mapping=data: mapping[k] and k))
</code></pre>
| 1 | 2009-10-12T17:52:35Z | [
"python",
"dictionary"
] |
Efficient way to find the largest key in a dictionary with non-zero value | 1,555,968 | <p>I'm new Python and trying to implement code in a more Pythonic and efficient fashion.
Given a dictionary with numeric keys and values, what is the best way to find the largest key with a non-zero value?</p>
<p>Thanks</p>
| 5 | 2009-10-12T17:48:22Z | 1,556,050 | <p>To get the largest key, you can use the <a href="http://docs.python.org/3.1/library/functions.html#max"><code>max</code></a> function and inspect the keys like this:</p>
<pre><code>max(x.iterkeys())
</code></pre>
<p>To filter out ones where the value is 0, you can use a <a href="http://docs.python.org/reference/expressions.html#grammar-token-generator%5Fexpression"><em>generator expression</em></a>:</p>
<pre><code>(k for k, v in x.iteritems() if v != 0)
</code></pre>
<p>You can combine these to get what you are looking for (since <code>max</code> takes only one argument, the parentheses around the generator expression can be dropped):</p>
<pre><code>max(k for k, v in x.iteritems() if v != 0)
</code></pre>
| 8 | 2009-10-12T18:09:11Z | [
"python",
"dictionary"
] |
Efficient way to find the largest key in a dictionary with non-zero value | 1,555,968 | <p>I'm new Python and trying to implement code in a more Pythonic and efficient fashion.
Given a dictionary with numeric keys and values, what is the best way to find the largest key with a non-zero value?</p>
<p>Thanks</p>
| 5 | 2009-10-12T17:48:22Z | 1,556,417 | <p>If I were you and speed was a big concern, I'd probably create a new container class "DictMax" that'd keep track of it's largest non-zero value elements by having an internal stack of indexes, where the top element of the stack is always the key of the largest element in the dictionary. That way you'd get the largest element in constant time everytime.</p>
| 0 | 2009-10-12T19:25:51Z | [
"python",
"dictionary"
] |
Python AppEngine And HTML | 1,555,978 | <p>I have a simple Hello World application in Python that i'm using with AppEngine, but i want to insert this in a HTML file, like this: I have a file called test.html and on it i have this snippet:</p>
<pre><code><center><img src="test.png></center>
// Here comes the Python App //
</code></pre>
<p>I want to put the output of the Python application in this space, like i can do with Servlets(Java).</p>
<p>Regards.</p>
| 0 | 2009-10-12T17:49:30Z | 1,556,000 | <p>You should work through the getting started docs at the AppEngine site. Specifically around templates:
<a href="http://code.google.com/appengine/docs/python/gettingstarted/templates.html" rel="nofollow">http://code.google.com/appengine/docs/python/gettingstarted/templates.html</a>.</p>
| 4 | 2009-10-12T17:54:12Z | [
"python",
"html",
"integrate"
] |
Python AppEngine And HTML | 1,555,978 | <p>I have a simple Hello World application in Python that i'm using with AppEngine, but i want to insert this in a HTML file, like this: I have a file called test.html and on it i have this snippet:</p>
<pre><code><center><img src="test.png></center>
// Here comes the Python App //
</code></pre>
<p>I want to put the output of the Python application in this space, like i can do with Servlets(Java).</p>
<p>Regards.</p>
| 0 | 2009-10-12T17:49:30Z | 1,556,010 | <p>Use the Django templates - the module comes built in with the app engine. I've used it <a href="http://github.com/sudhirj/mappr/blob/master/main.py" rel="nofollow">here</a> on line 42. The template used is <a href="http://github.com/sudhirj/mappr/blob/master/templates/index.html" rel="nofollow">here</a>.</p>
| 2 | 2009-10-12T17:57:08Z | [
"python",
"html",
"integrate"
] |
Python AppEngine And HTML | 1,555,978 | <p>I have a simple Hello World application in Python that i'm using with AppEngine, but i want to insert this in a HTML file, like this: I have a file called test.html and on it i have this snippet:</p>
<pre><code><center><img src="test.png></center>
// Here comes the Python App //
</code></pre>
<p>I want to put the output of the Python application in this space, like i can do with Servlets(Java).</p>
<p>Regards.</p>
| 0 | 2009-10-12T17:49:30Z | 12,961,478 | <p>I would really recommend using a boilerplate template
<a href="https://github.com/coto/gae-boilerplate" rel="nofollow">https://github.com/coto/gae-boilerplate</a>
This would give you the layout and template structure for developing useful and professional sites </p>
| 1 | 2012-10-18T18:37:42Z | [
"python",
"html",
"integrate"
] |
In Django, How Do I Move Images When A Dynamic Path Changes? | 1,556,040 | <p>I have a Django app with an image field (a custom ThumbnailImageField type) that auto-generates the file path for an image based on the title, type, and country of the item the image is attached to (upload_ to = get_ image_path). Here's how: </p>
<pre><code>def get_image_path(instance, filename):
dir = 'images'
subdir = instance.get_type_display()
sub_subdir = 'other'
if instance.country:
sub_subdir = instance.country.name
name = instance.name
extension = filename.split('.')[-1]
return "%s/%s/%s/%s.%s" % (dir, subdir, sub_subdir, name, extension)
</code></pre>
<p>It works great, except in one situation: When I rename an item, change the country it's from, or change the category it's in, the image becomes a dead link because it generates a new image path without moving the orignal file.</p>
<p>So, the magic question:</p>
<p>Is there some save function in Django that I can hook into and override that will let me have the original object and the proposed values and compare them so I know where the image path was and where it will need to go (and then use this info to move/rename in code)?</p>
| 1 | 2009-10-12T18:03:34Z | 1,556,049 | <p>You probably want to look into signals:</p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/signals/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/signals/</a></p>
<p>In particular, the django.db.models.signals.pre_save signal:</p>
<p><a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#pre%5Fsave" rel="nofollow">http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#pre%5Fsave</a></p>
| 3 | 2009-10-12T18:09:06Z | [
"python",
"django",
"django-models"
] |
How to select an item from a list with known percentages in Python | 1,556,232 | <p>I wish to select a random word from a list where the is a known chance for each word, for example:</p>
<p>Fruit with Probability </p>
<p>Orange 0.10
Apple 0.05
Mango 0.15
etc</p>
<p>How would be the best way of implementing this? The actual list I will take from is up to 100 items longs and the % do not all tally to 100 % they do fall short to account for the items that had a really low chance of occurrence. I would ideally like to take this from a CSV which is where I store this data. This is not a time critical task.</p>
<p>Thank you for any advice on how best to proceed.</p>
| 1 | 2009-10-12T18:46:00Z | 1,556,285 | <p>One solution is to normalize the probabilities to integers and then repeat each element once per value (e.g. a list with 2 Oranges, 1 Apple, 3 Mangos). This is incredibly easy to do (<code>from random import choice</code>). If that is not practical, try the code <a href="http://code.activestate.com/recipes/498229/" rel="nofollow">here</a>.</p>
| -1 | 2009-10-12T18:55:22Z | [
"python",
"algorithm"
] |
How to select an item from a list with known percentages in Python | 1,556,232 | <p>I wish to select a random word from a list where the is a known chance for each word, for example:</p>
<p>Fruit with Probability </p>
<p>Orange 0.10
Apple 0.05
Mango 0.15
etc</p>
<p>How would be the best way of implementing this? The actual list I will take from is up to 100 items longs and the % do not all tally to 100 % they do fall short to account for the items that had a really low chance of occurrence. I would ideally like to take this from a CSV which is where I store this data. This is not a time critical task.</p>
<p>Thank you for any advice on how best to proceed.</p>
| 1 | 2009-10-12T18:46:00Z | 1,556,302 | <pre><code>import random
d= {'orange': 0.10, 'mango': 0.15, 'apple': 0.05}
weightedArray = []
for k in d:
weightedArray+=[k]*int(d[k]*100)
random.choice(weightedArray)
</code></pre>
<p><strong>EDITS</strong></p>
<p>This is essentially what Brian said above.</p>
| -1 | 2009-10-12T18:59:24Z | [
"python",
"algorithm"
] |
How to select an item from a list with known percentages in Python | 1,556,232 | <p>I wish to select a random word from a list where the is a known chance for each word, for example:</p>
<p>Fruit with Probability </p>
<p>Orange 0.10
Apple 0.05
Mango 0.15
etc</p>
<p>How would be the best way of implementing this? The actual list I will take from is up to 100 items longs and the % do not all tally to 100 % they do fall short to account for the items that had a really low chance of occurrence. I would ideally like to take this from a CSV which is where I store this data. This is not a time critical task.</p>
<p>Thank you for any advice on how best to proceed.</p>
| 1 | 2009-10-12T18:46:00Z | 1,556,327 | <pre><code>lst = [ ('Orange', 0.10), ('Apple', 0.05), ('Mango', 0.15), ('etc', 0.69) ]
x = 0.0
lst2 = []
for fruit, chance in lst:
tup = (x, fruit)
lst2.append(tup)
x += chance
tup = (x, None)
lst2.append(tup)
import random
def pick_one(lst2):
if lst2[0][1] is None:
raise ValueError, "no valid values to choose"
while True:
r = random.random()
for x, fruit in reversed(lst2):
if x <= r:
if fruit is None:
break # try again with a different random value
else:
return fruit
pick_one(lst2)
</code></pre>
<p>This builds a new list, with ascending values representing the range of values that choose a fruit; then pick_one() walks backward down the list, looking for a value that is <= the current random value. We put a "sentinel" value on the end of the list; if the values don't reach 1.0, there is a chance of a random value that shouldn't match anything, and it will match the sentinel value and then be rejected. random.random() returns a random value in the range [0.0, 1.0) so it is certain to match something in the list eventually.</p>
<p>The nice thing here is that you should be able to have one value with a 0.000001 chance of matching, and it should actually match with that frequency; the other solutions, where you make a list with the items repeated and just use random.choice() to choose one, would require a list with a million items in it to handle this case.</p>
| 1 | 2009-10-12T19:05:42Z | [
"python",
"algorithm"
] |
How to select an item from a list with known percentages in Python | 1,556,232 | <p>I wish to select a random word from a list where the is a known chance for each word, for example:</p>
<p>Fruit with Probability </p>
<p>Orange 0.10
Apple 0.05
Mango 0.15
etc</p>
<p>How would be the best way of implementing this? The actual list I will take from is up to 100 items longs and the % do not all tally to 100 % they do fall short to account for the items that had a really low chance of occurrence. I would ideally like to take this from a CSV which is where I store this data. This is not a time critical task.</p>
<p>Thank you for any advice on how best to proceed.</p>
| 1 | 2009-10-12T18:46:00Z | 1,556,403 | <p>You can pick items with weighted probabilities if you assign each item a number range proportional to its probability, pick a random number between zero and the sum of the ranges and find what item matches it. The following class does exactly that:</p>
<pre><code>from random import random
class WeightedChoice(object):
def __init__(self, weights):
"""Pick items with weighted probabilities.
weights
a sequence of tuples of item and it's weight.
"""
self._total_weight = 0.
self._item_levels = []
for item, weight in weights:
self._total_weight += weight
self._item_levels.append((self._total_weight, item))
def pick(self):
pick = self._total_weight * random()
for level, item in self._item_levels:
if level >= pick:
return item
</code></pre>
<p>You can then load the CSV file with the <code>csv</code> module and feed it to the <code>WeightedChoice</code> class:</p>
<pre><code>import csv
weighed_items = [(item,float(weight)) for item,weight in csv.reader(open('file.csv'))]
picker = WeightedChoice(weighed_items)
print(picker.pick())
</code></pre>
| 2 | 2009-10-12T19:22:28Z | [
"python",
"algorithm"
] |
How to select an item from a list with known percentages in Python | 1,556,232 | <p>I wish to select a random word from a list where the is a known chance for each word, for example:</p>
<p>Fruit with Probability </p>
<p>Orange 0.10
Apple 0.05
Mango 0.15
etc</p>
<p>How would be the best way of implementing this? The actual list I will take from is up to 100 items longs and the % do not all tally to 100 % they do fall short to account for the items that had a really low chance of occurrence. I would ideally like to take this from a CSV which is where I store this data. This is not a time critical task.</p>
<p>Thank you for any advice on how best to proceed.</p>
| 1 | 2009-10-12T18:46:00Z | 1,556,471 | <pre><code>lst = [ ('Orange', 0.10), ('Apple', 0.05), ('Mango', 0.15), ('etc', 0.69) ]
x = 0.0
lst2 = []
for fruit, chance in lst:
low = x
high = x + chance
tup = (low, high, fruit)
lst2.append(tup)
x += chance
if x > 1.0:
raise ValueError, "chances add up to more than 100%"
low = x
high = 1.0
tup = (low, high, None)
lst2.append(tup)
import random
def pick_one(lst2):
if lst2[0][2] is None:
raise ValueError, "no valid values to choose"
while True:
r = random.random()
for low, high, fruit in lst2:
if low <= r < high:
if fruit is None:
break # try again with a different random value
else:
return fruit
pick_one(lst2)
# test it 10,000 times
d = {}
for i in xrange(10000):
x = pick_one(lst2)
if x in d:
d[x] += 1
else:
d[x] = 1
</code></pre>
<p>I think this is a little clearer. Instead of a tricky way of representing ranges as ascending values, we just keep ranges. Because we are testing ranges, we can simply walk forward through the lst2 values; no need to use <code>reversed()</code>.</p>
| 0 | 2009-10-12T19:39:23Z | [
"python",
"algorithm"
] |
How to select an item from a list with known percentages in Python | 1,556,232 | <p>I wish to select a random word from a list where the is a known chance for each word, for example:</p>
<p>Fruit with Probability </p>
<p>Orange 0.10
Apple 0.05
Mango 0.15
etc</p>
<p>How would be the best way of implementing this? The actual list I will take from is up to 100 items longs and the % do not all tally to 100 % they do fall short to account for the items that had a really low chance of occurrence. I would ideally like to take this from a CSV which is where I store this data. This is not a time critical task.</p>
<p>Thank you for any advice on how best to proceed.</p>
| 1 | 2009-10-12T18:46:00Z | 1,556,481 | <p>What you want is to draw from a <a href="http://en.wikipedia.org/wiki/Multinomial%5Fdistribution" rel="nofollow">multinomial distribution</a>. Assuming you have two lists of items and probabilities, and the probabilities sum to 1 (if not, just add some default value to cover the extra):</p>
<pre><code>def choose(items,chances):
import random
p = chances[0]
x = random.random()
i = 0
while x > p :
i = i + 1
p = p + chances[i]
return items[i]
</code></pre>
| 2 | 2009-10-12T19:43:30Z | [
"python",
"algorithm"
] |
Circular import dependency in Python | 1,556,387 | <p>Let's say I have the following directory structure:</p>
<pre><code>a\
__init__.py
b\
__init__.py
c\
__init__.py
c_file.py
d\
__init__.py
d_file.py
</code></pre>
<p>In the <code>a</code> package's <code>__init__.py</code>, the <code>c</code> package is imported. But <code>c_file.py</code> imports <code>a.b.d</code>.</p>
<p>The program fails, saying <code>b</code> doesn't exist when <code>c_file.py</code> tries to import <code>a.b.d</code>. (And it really doesn't exist, because we were in the middle of importing it.)</p>
<p>How can this problem be remedied?</p>
| 57 | 2009-10-12T19:19:30Z | 1,556,429 | <p>You may defer the import, for example in <code>a/__init__.py</code>:</p>
<pre><code>def my_function():
from a.b.c import Blah
return Blah()
</code></pre>
<p>that is, defer the import until it is really needed. However, I would also have a close look at my package definitions/uses, as a cyclic dependency like the one pointed out might indicate a design problem.</p>
| 128 | 2009-10-12T19:27:53Z | [
"python",
"dependencies",
"circular-dependency",
"python-import"
] |
Circular import dependency in Python | 1,556,387 | <p>Let's say I have the following directory structure:</p>
<pre><code>a\
__init__.py
b\
__init__.py
c\
__init__.py
c_file.py
d\
__init__.py
d_file.py
</code></pre>
<p>In the <code>a</code> package's <code>__init__.py</code>, the <code>c</code> package is imported. But <code>c_file.py</code> imports <code>a.b.d</code>.</p>
<p>The program fails, saying <code>b</code> doesn't exist when <code>c_file.py</code> tries to import <code>a.b.d</code>. (And it really doesn't exist, because we were in the middle of importing it.)</p>
<p>How can this problem be remedied?</p>
| 57 | 2009-10-12T19:19:30Z | 1,556,444 | <p>If a depends on c and c depends on a, aren't they actually the same unit then?</p>
<p>You should really examine why you have split a and c into two packages, because either you have some code you should split off into another package (to make them both depend on that new package, but not each other), or you should merge them into one package.</p>
| 53 | 2009-10-12T19:33:28Z | [
"python",
"dependencies",
"circular-dependency",
"python-import"
] |
Circular import dependency in Python | 1,556,387 | <p>Let's say I have the following directory structure:</p>
<pre><code>a\
__init__.py
b\
__init__.py
c\
__init__.py
c_file.py
d\
__init__.py
d_file.py
</code></pre>
<p>In the <code>a</code> package's <code>__init__.py</code>, the <code>c</code> package is imported. But <code>c_file.py</code> imports <code>a.b.d</code>.</p>
<p>The program fails, saying <code>b</code> doesn't exist when <code>c_file.py</code> tries to import <code>a.b.d</code>. (And it really doesn't exist, because we were in the middle of importing it.)</p>
<p>How can this problem be remedied?</p>
| 57 | 2009-10-12T19:19:30Z | 11,521,614 | <p>Another solution is to use a proxy for the d_file.</p>
<p>For example, let's say that you want to share the blah class with the c_file. The d_file thus contains:</p>
<pre><code>class blah:
def __init__(self):
print("blah")
</code></pre>
<p>Here is what you enter in c_file.py:</p>
<pre><code># do not import the d_file !
# instead, use a place holder for the proxy of d_file
# it will be set by a's __init__.py after imports are done
d_file = None
def c_blah(): # a function that calls d_file's blah
d_file.blah()
</code></pre>
<p>And in a's <strong>init</strong>.py:</p>
<pre><code>from b.c import c_file
from b.d import d_file
class Proxy(object): # module proxy
pass
d_file_proxy = Proxy()
# now you need to explicitly list the class(es) exposed by d_file
d_file_proxy.blah = d_file.blah
# finally, share the proxy with c_file
c_file.d_file = d_file_proxy
# c_file is now able to call d_file.blah
c_file.c_blah()
</code></pre>
| -3 | 2012-07-17T11:33:26Z | [
"python",
"dependencies",
"circular-dependency",
"python-import"
] |
Circular import dependency in Python | 1,556,387 | <p>Let's say I have the following directory structure:</p>
<pre><code>a\
__init__.py
b\
__init__.py
c\
__init__.py
c_file.py
d\
__init__.py
d_file.py
</code></pre>
<p>In the <code>a</code> package's <code>__init__.py</code>, the <code>c</code> package is imported. But <code>c_file.py</code> imports <code>a.b.d</code>.</p>
<p>The program fails, saying <code>b</code> doesn't exist when <code>c_file.py</code> tries to import <code>a.b.d</code>. (And it really doesn't exist, because we were in the middle of importing it.)</p>
<p>How can this problem be remedied?</p>
| 57 | 2009-10-12T19:19:30Z | 19,186,096 | <p>I've wondered this a couple times (usually while dealing with models that need to know about each other). The simple solution is just to import the whole module, then reference the thing that you need.</p>
<p>So instead of doing </p>
<pre><code>from models import Student
</code></pre>
<p>in one, and </p>
<pre><code>from models import Classroom
</code></pre>
<p>in the other, just do</p>
<pre><code>import models
</code></pre>
<p>in one of them, then call models.Classroom when you need it.</p>
| 14 | 2013-10-04T16:18:32Z | [
"python",
"dependencies",
"circular-dependency",
"python-import"
] |
Circular import dependency in Python | 1,556,387 | <p>Let's say I have the following directory structure:</p>
<pre><code>a\
__init__.py
b\
__init__.py
c\
__init__.py
c_file.py
d\
__init__.py
d_file.py
</code></pre>
<p>In the <code>a</code> package's <code>__init__.py</code>, the <code>c</code> package is imported. But <code>c_file.py</code> imports <code>a.b.d</code>.</p>
<p>The program fails, saying <code>b</code> doesn't exist when <code>c_file.py</code> tries to import <code>a.b.d</code>. (And it really doesn't exist, because we were in the middle of importing it.)</p>
<p>How can this problem be remedied?</p>
| 57 | 2009-10-12T19:19:30Z | 32,302,200 | <p>The problem is that when running from a directory, by default only the packages that are sub directories are visible as candidate imports, so you cannot import a.b.d. You can however import b.d. since b is a sub package of a.</p>
<p>If you really want to import a.b.d in <code>c/__init__.py</code> you can accomplish this by changing the system path to be one directory above a and change the import in <code>a/__init__.py</code> to be import a.b.c.</p>
<p>Your <code>a/__init__.py</code> should look like this:</p>
<pre><code>import sys
import os
# set sytem path to be directory above so that a can be a
# package namespace
DIRECTORY_SCRIPT = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0,DIRECTORY_SCRIPT+"/..")
import a.b.c
</code></pre>
<p>An additional difficulty arises when you want to run modules in c as scripts. Here the packages a and b do not exist. You can hack the <code>__int__.py</code> in the c directory to point the sys.path to the top-level directory and then import <code>__init__</code> in any modules inside c to be able to use the full path to import a.b.d. I doubt that it is good practice to import <code>__init__.py</code> but it has worked for my use cases.</p>
| 0 | 2015-08-30T23:33:12Z | [
"python",
"dependencies",
"circular-dependency",
"python-import"
] |
jinja2: html escape variables | 1,556,554 | <p>how do I html-escape dangerous unsanitized input in jinja2?</p>
<p>Can I do it inside the template or must it be done in python code?</p>
<p>I have a variable that may contain da<ngero>u&s chars. How do I escape it in jinja2</p>
| 13 | 2009-10-12T20:00:49Z | 1,556,570 | <p>e.g.</p>
<pre><code>{{ user.username|e }}
</code></pre>
<p>Pipe it through the <code>|e</code> filter</p>
<p><a href="http://jinja.pocoo.org/2/documentation/templates#escape">Jinija: Template Designer Documentation -> Builtin Filters: Escape</a></p>
| 23 | 2009-10-12T20:03:50Z | [
"python",
"security",
"escaping",
"jinja2"
] |
jinja2: html escape variables | 1,556,554 | <p>how do I html-escape dangerous unsanitized input in jinja2?</p>
<p>Can I do it inside the template or must it be done in python code?</p>
<p>I have a variable that may contain da<ngero>u&s chars. How do I escape it in jinja2</p>
| 13 | 2009-10-12T20:00:49Z | 3,820,710 | <p>You could also tell the environment to autoescape everything:</p>
<pre><code>e = Environment(loader=fileloader, autoescape=True)
</code></pre>
<p>note: in jinja1 this is auto_escape</p>
| 11 | 2010-09-29T10:25:13Z | [
"python",
"security",
"escaping",
"jinja2"
] |
jinja2: html escape variables | 1,556,554 | <p>how do I html-escape dangerous unsanitized input in jinja2?</p>
<p>Can I do it inside the template or must it be done in python code?</p>
<p>I have a variable that may contain da<ngero>u&s chars. How do I escape it in jinja2</p>
| 13 | 2009-10-12T20:00:49Z | 10,063,883 | <p>If you want to escape html in your programme, you can do it like this(example):</p>
<pre><code>>>> import jinja2
>>> jinja2.__version__
'2.6'
>>> a
'<script>alert("yy")</script>'
>>> jinja2.escape(a)
Markup(u'&lt;script&gt;alert(&#34;yy&#34;)&lt;/script&gt;')
>>> str(jinja2.escape(a))
'&lt;script&gt;alert(&#34;yy&#34;)&lt;/script&gt;'
</code></pre>
| 4 | 2012-04-08T15:16:27Z | [
"python",
"security",
"escaping",
"jinja2"
] |
jinja2: html escape variables | 1,556,554 | <p>how do I html-escape dangerous unsanitized input in jinja2?</p>
<p>Can I do it inside the template or must it be done in python code?</p>
<p>I have a variable that may contain da<ngero>u&s chars. How do I escape it in jinja2</p>
| 13 | 2009-10-12T20:00:49Z | 14,468,257 | <p>Flask has a built in <code>tojson</code> filter:</p>
<p><a href="http://flask.pocoo.org/docs/templating/#standard-filters" rel="nofollow">http://flask.pocoo.org/docs/templating/#standard-filters</a></p>
| 1 | 2013-01-22T21:22:38Z | [
"python",
"security",
"escaping",
"jinja2"
] |
Recommendations for perl-to-python interoperation? | 1,556,668 | <p>We have a sizable code base in Perl. For the forseeable future, our codebase will remain in Perl. However, we're looking into adding a GUI-based dashboard utility. We are considering writing the dashboard in Python (using tkinter or wx). The problem, however, is that we would like to leverage our existing Perl codebase in the Python GUI.</p>
<p>So... any suggestions on how achieve this? We are considering a few options:</p>
<ol>
<li>Write executables (in Perl) that mimic function calls; invoke those Perl executables in python as system calls.</li>
<li>Write Perl executables on-the-fly inside the Python dashboard, and invoke the (temporary) Perl executable.</li>
<li>Find some kind of Perl-to-Python converter or binding.</li>
</ol>
<p>Any other ideas? I'd love to hear if other people have confronted this problem. Unfortunately, it's not an option to convert the codebase itself to Python at this time.</p>
| 1 | 2009-10-12T20:22:08Z | 1,556,796 | <p>Try the CPAN distribution <a href="http://search.cpan.org/perldoc/Python" rel="nofollow">Python (pyperl)</a> for interfacing with python code.</p>
| 5 | 2009-10-12T20:40:50Z | [
"python",
"perl"
] |
Recommendations for perl-to-python interoperation? | 1,556,668 | <p>We have a sizable code base in Perl. For the forseeable future, our codebase will remain in Perl. However, we're looking into adding a GUI-based dashboard utility. We are considering writing the dashboard in Python (using tkinter or wx). The problem, however, is that we would like to leverage our existing Perl codebase in the Python GUI.</p>
<p>So... any suggestions on how achieve this? We are considering a few options:</p>
<ol>
<li>Write executables (in Perl) that mimic function calls; invoke those Perl executables in python as system calls.</li>
<li>Write Perl executables on-the-fly inside the Python dashboard, and invoke the (temporary) Perl executable.</li>
<li>Find some kind of Perl-to-Python converter or binding.</li>
</ol>
<p>Any other ideas? I'd love to hear if other people have confronted this problem. Unfortunately, it's not an option to convert the codebase itself to Python at this time.</p>
| 1 | 2009-10-12T20:22:08Z | 1,556,811 | <p>You can spawn a child process and use an IPC mechanism like sockets or STDIO, or even embed <a href="http://search.cpan.org/~gaas/pyperl-1.0/perlmodule.pod" rel="nofollow">one interpreter</a> <a href="http://search.cpan.org/~nine/Inline-Python-0.29/Python.pod" rel="nofollow">in the other</a>.</p>
<p>But why switch languages when Perl offers several Tk (<a href="http://search.cpan.org/perldoc/Tk" rel="nofollow">Tk</a>, <a href="http://search.cpan.org/perldoc/Tkx" rel="nofollow">Tkx</a>, and <a href="http://search.cpan.org/perldoc/Tcl%3A%3ATk" rel="nofollow">Tcl::Tk</a>) bindings and a very capable <a href="http://search.cpan.org/perldoc/Wx" rel="nofollow">Wx binding</a>?</p>
<p>I have written and distributed GUI projects with Perl's Tk and Wx libraries.</p>
<p>If you are need the ability to create stand-alone executables, check out <a href="http://search.cpan.org/perldoc/PAR%3A%3APacker" rel="nofollow">PAR::Packer</a>, <a href="http://www.activestate.com/perl%5Fdev%5Fkit/" rel="nofollow">ActiveState's PerlApp</a>, and <a href="http://www.cava.co.uk/" rel="nofollow">Cava Pacakger</a>.</p>
| 6 | 2009-10-12T20:43:09Z | [
"python",
"perl"
] |
Recommendations for perl-to-python interoperation? | 1,556,668 | <p>We have a sizable code base in Perl. For the forseeable future, our codebase will remain in Perl. However, we're looking into adding a GUI-based dashboard utility. We are considering writing the dashboard in Python (using tkinter or wx). The problem, however, is that we would like to leverage our existing Perl codebase in the Python GUI.</p>
<p>So... any suggestions on how achieve this? We are considering a few options:</p>
<ol>
<li>Write executables (in Perl) that mimic function calls; invoke those Perl executables in python as system calls.</li>
<li>Write Perl executables on-the-fly inside the Python dashboard, and invoke the (temporary) Perl executable.</li>
<li>Find some kind of Perl-to-Python converter or binding.</li>
</ol>
<p>Any other ideas? I'd love to hear if other people have confronted this problem. Unfortunately, it's not an option to convert the codebase itself to Python at this time.</p>
| 1 | 2009-10-12T20:22:08Z | 1,556,843 | <p>I'd avoid inter-language calls if possible; fragility and massive increases in dependencies await you down this road. However, there is...</p>
<p><a href="http://search.cpan.org/perldoc/Inline%3A%3APython" rel="nofollow">Inline::Python</a></p>
<p>If python must be used, the <code>Inline::*</code> series of modules have been generally well received. This lets you write python inside a perl script. You still have to write perl but it would let you use python libraries inside perl scripts. It will make things more difficult to debug, though.</p>
| 1 | 2009-10-12T20:47:34Z | [
"python",
"perl"
] |
Recommendations for perl-to-python interoperation? | 1,556,668 | <p>We have a sizable code base in Perl. For the forseeable future, our codebase will remain in Perl. However, we're looking into adding a GUI-based dashboard utility. We are considering writing the dashboard in Python (using tkinter or wx). The problem, however, is that we would like to leverage our existing Perl codebase in the Python GUI.</p>
<p>So... any suggestions on how achieve this? We are considering a few options:</p>
<ol>
<li>Write executables (in Perl) that mimic function calls; invoke those Perl executables in python as system calls.</li>
<li>Write Perl executables on-the-fly inside the Python dashboard, and invoke the (temporary) Perl executable.</li>
<li>Find some kind of Perl-to-Python converter or binding.</li>
</ol>
<p>Any other ideas? I'd love to hear if other people have confronted this problem. Unfortunately, it's not an option to convert the codebase itself to Python at this time.</p>
| 1 | 2009-10-12T20:22:08Z | 1,557,216 | <p>Well, if you really want to write the GUI in another language (which, seriously, is just a bad idea, since it will cost you more than it could ever benefit you), the thing you should do is the following:</p>
<ol>
<li>Document your Perl app in terms of the services it provides. You should do it with XML Schema Definition - XSD - for the data types and Web Service Description Language - WSDL - for the actual service.</li>
<li>Implement the services in Perl, possibly using Catalyst::Controller::SOAP, or just XML::Compile::SOAP.</li>
<li>Consume the services from your whatever-language GUI interface.</li>
<li>Profit.</li>
</ol>
<p>But honestly, I really suggest you taking a look at the Perl GTK2 binding, it is awesome, including features such as implementing a Gtk class entirely in Perl and using it as argument to a function written in C - for instance, you can write a model class for a gtk tree entirely in Perl.</p>
| 2 | 2009-10-12T22:11:42Z | [
"python",
"perl"
] |
Recommendations for perl-to-python interoperation? | 1,556,668 | <p>We have a sizable code base in Perl. For the forseeable future, our codebase will remain in Perl. However, we're looking into adding a GUI-based dashboard utility. We are considering writing the dashboard in Python (using tkinter or wx). The problem, however, is that we would like to leverage our existing Perl codebase in the Python GUI.</p>
<p>So... any suggestions on how achieve this? We are considering a few options:</p>
<ol>
<li>Write executables (in Perl) that mimic function calls; invoke those Perl executables in python as system calls.</li>
<li>Write Perl executables on-the-fly inside the Python dashboard, and invoke the (temporary) Perl executable.</li>
<li>Find some kind of Perl-to-Python converter or binding.</li>
</ol>
<p>Any other ideas? I'd love to hear if other people have confronted this problem. Unfortunately, it's not an option to convert the codebase itself to Python at this time.</p>
| 1 | 2009-10-12T20:22:08Z | 1,557,721 | <p>I'd think the major criterion for any qualified answer would involve the details of the existing codebase. How is this Perl code called and how does it return it's results?</p>
<p>A collection of command line utilities returning results through reasonably good textual output ("good" as in "amenable to further machine parsing" or "pipeline friendly") ... should be reasonably easy to call from any programming language (and Python's excellent <code>subprocess</code> and <code>multiprocessing</code> modules in particular). A collection of web CGI or other modules layered between Apache and some DBMS system could still be accessed with things like <code>urlopen2</code> or <a href="http://wwwsearch.sourceforge.net/mechanize/src/README-0.1.2b.html" rel="nofollow"><code>mechanize</code></a> -- but it might be better to bypass the Perl code and write Python to query the underlying (presumably canonical) model (data store).</p>
<p>If the majority of the codebase is a set of libraries or modules ... and the functionality that your proposed dashboard requires isn't already exposed via some higher level mechanism (some command line interface, networking protocol, etc) ... then it's basically insane to consider interfacing to it through any language other than Perl. (Unless, by some strange and extremely unlikely twist of fate, your existing codebase and your intended implementation target are both already stable under <a href="http://www.parrot.org/" rel="nofollow">Parrot</a>).</p>
<p>Let's ask a different, broader, question: <strong>What interface to you intend to use between your dashboard and your existing code base?</strong></p>
<p>This question is paramount regardless of your choice of implementation language. If you write the dashboard in Perl it still needs to call into your existing code base in some way. You probably need to fix-up your code base to implement support for whatever your going to use for your dashboard. At the point where your codebase supports the necessary API (has command line or IPC protocol calls into the desired functionality which return results over any reasonable IPC mechanism) ... then your choice of dashboard implementation language will be essentially arbitrary.</p>
| 1 | 2009-10-13T00:51:11Z | [
"python",
"perl"
] |
Recommendations for perl-to-python interoperation? | 1,556,668 | <p>We have a sizable code base in Perl. For the forseeable future, our codebase will remain in Perl. However, we're looking into adding a GUI-based dashboard utility. We are considering writing the dashboard in Python (using tkinter or wx). The problem, however, is that we would like to leverage our existing Perl codebase in the Python GUI.</p>
<p>So... any suggestions on how achieve this? We are considering a few options:</p>
<ol>
<li>Write executables (in Perl) that mimic function calls; invoke those Perl executables in python as system calls.</li>
<li>Write Perl executables on-the-fly inside the Python dashboard, and invoke the (temporary) Perl executable.</li>
<li>Find some kind of Perl-to-Python converter or binding.</li>
</ol>
<p>Any other ideas? I'd love to hear if other people have confronted this problem. Unfortunately, it's not an option to convert the codebase itself to Python at this time.</p>
| 1 | 2009-10-12T20:22:08Z | 1,557,825 | <p>I hate to be another one in the chorus, but...</p>
<ol>
<li>Avoid the use of an alternate language</li>
<li>Use Wx so it's native look and feel makes the application look "real" to non-technical audiences.</li>
<li>Download the Padre source code and see how it does Wx Perl code, then steal rampantly from it's best tricks or maybe just gut it and use the application skeleton (using the Artistic half of the Perl dual license to make it legal).</li>
<li>Build your own Strawberry Perl subclass to package the application as an MSI installer and push it out across the corporate Active Directory domain.</li>
</ol>
<p>Of course, I only say all this because you said "Dashboard" which I read as "Corporate", which then makes me assume a Microsoft AD network...</p>
| 7 | 2009-10-13T01:35:51Z | [
"python",
"perl"
] |
Recommendations for perl-to-python interoperation? | 1,556,668 | <p>We have a sizable code base in Perl. For the forseeable future, our codebase will remain in Perl. However, we're looking into adding a GUI-based dashboard utility. We are considering writing the dashboard in Python (using tkinter or wx). The problem, however, is that we would like to leverage our existing Perl codebase in the Python GUI.</p>
<p>So... any suggestions on how achieve this? We are considering a few options:</p>
<ol>
<li>Write executables (in Perl) that mimic function calls; invoke those Perl executables in python as system calls.</li>
<li>Write Perl executables on-the-fly inside the Python dashboard, and invoke the (temporary) Perl executable.</li>
<li>Find some kind of Perl-to-Python converter or binding.</li>
</ol>
<p>Any other ideas? I'd love to hear if other people have confronted this problem. Unfortunately, it's not an option to convert the codebase itself to Python at this time.</p>
| 1 | 2009-10-12T20:22:08Z | 1,560,979 | <p>Interesting project: I would opt for loose-coupling and consider an XML-RPC or JSON based approach.</p>
| 1 | 2009-10-13T15:28:32Z | [
"python",
"perl"
] |
Should you import all classes you use in Python? | 1,556,766 | <p>Python's lack of static typing makes it possible to use and rely on classes without importing them. Should you import them anyway? Does it matter?</p>
<h3>Example</h3>
<p><strong>someclass.py</strong></p>
<pre><code>class SomeClass:
def __init__(self, some_value):
self.some_value = some_value
</code></pre>
<p><strong>someclient.py</strong></p>
<pre><code>class SomeClient:
def __init__(self, some_class_instance):
self.some_class_helper = some_class_instance
</code></pre>
<p>Here, the functionality of <code>SomeClient</code> clearly relies on <code>SomeClass</code> or at least something that behaves like it. However, someclient.py will work just fine without <code>import someclass</code>. Is this ok? It feels wrong to use something without saying anywhere that you're even using it.</p>
| 2 | 2009-10-12T20:35:36Z | 1,556,784 | <p>Importing <code>SomeClass</code> won't make any difference to how that code works.</p>
<p>If you're worried about making the code understandable, comment the fact that <code>SomeClient</code> expects a <code>SomeClass</code> instance, and/or document it in the docstring.</p>
<p>If you want to <em>police</em> the fact that <code>SomeClient</code> requires a <code>SomeClass</code> instance, you can <code>assert</code> it:</p>
<pre><code>class SomeClient:
def __init__(self, some_class_instance):
assert isinstance(some_class_instance, SomeClass)
self.some_class_helper = some_class_instance
</code></pre>
<p>which <em>will</em> require importing <code>SomeClass</code>. But note that you're being rather restrictive there - it precludes using a Mock <code>SomeClass</code> for testing purposes, for example. (There's a lengthy rant about this here: <a href="http://www.canonical.org/~kragen/isinstance/" rel="nofollow">"isinstance() considered harmful"</a>.)</p>
| 5 | 2009-10-12T20:38:44Z | [
"python",
"coding-style"
] |
Should you import all classes you use in Python? | 1,556,766 | <p>Python's lack of static typing makes it possible to use and rely on classes without importing them. Should you import them anyway? Does it matter?</p>
<h3>Example</h3>
<p><strong>someclass.py</strong></p>
<pre><code>class SomeClass:
def __init__(self, some_value):
self.some_value = some_value
</code></pre>
<p><strong>someclient.py</strong></p>
<pre><code>class SomeClient:
def __init__(self, some_class_instance):
self.some_class_helper = some_class_instance
</code></pre>
<p>Here, the functionality of <code>SomeClient</code> clearly relies on <code>SomeClass</code> or at least something that behaves like it. However, someclient.py will work just fine without <code>import someclass</code>. Is this ok? It feels wrong to use something without saying anywhere that you're even using it.</p>
| 2 | 2009-10-12T20:35:36Z | 1,556,785 | <p>Yes, it's completely ok. <code>some_class_instance</code> might be anything, it doesn't have to be an instance of <code>SomeClass</code>. You might want to pass an instance that looks just like <code>SomeClass</code>, but uses a different implementation for testing purposes, for example.</p>
| 8 | 2009-10-12T20:38:56Z | [
"python",
"coding-style"
] |
Should you import all classes you use in Python? | 1,556,766 | <p>Python's lack of static typing makes it possible to use and rely on classes without importing them. Should you import them anyway? Does it matter?</p>
<h3>Example</h3>
<p><strong>someclass.py</strong></p>
<pre><code>class SomeClass:
def __init__(self, some_value):
self.some_value = some_value
</code></pre>
<p><strong>someclient.py</strong></p>
<pre><code>class SomeClient:
def __init__(self, some_class_instance):
self.some_class_helper = some_class_instance
</code></pre>
<p>Here, the functionality of <code>SomeClient</code> clearly relies on <code>SomeClass</code> or at least something that behaves like it. However, someclient.py will work just fine without <code>import someclass</code>. Is this ok? It feels wrong to use something without saying anywhere that you're even using it.</p>
| 2 | 2009-10-12T20:35:36Z | 1,556,817 | <p>In this case, you shouldn't import the class.</p>
<p>Python relies on what is called "<a href="http://docs.python.org/glossary.html#term-duck-typing" rel="nofollow">duck typing</a>" - if it walks like a duck and quacks like a duck, it might as well be a duck.</p>
<p>Your code doesn't care what class really gets passed in when the program runs. All it cares is that it acts just like "SomeClass" acts.</p>
<p><strong>duck-typing</strong></p>
<blockquote>
<p>A pythonic programming style which determines an objectâs type by
inspection of its method or attribute
signature rather than by explicit
relationship to some type object (âIf
it looks like a duck and quacks like a
duck, it must be a duck.â) By
emphasizing interfaces rather than
specific types, well-designed code
improves its flexibility by allowing
polymorphic substitution. Duck-typing
avoids tests using type() or
isinstance(). (Note, however, that
duck-typing can be complemented with
abstract base classes.) Instead, it
typically employs hasattr() tests or
EAFP programming.</p>
</blockquote>
| 4 | 2009-10-12T20:44:11Z | [
"python",
"coding-style"
] |
Should you import all classes you use in Python? | 1,556,766 | <p>Python's lack of static typing makes it possible to use and rely on classes without importing them. Should you import them anyway? Does it matter?</p>
<h3>Example</h3>
<p><strong>someclass.py</strong></p>
<pre><code>class SomeClass:
def __init__(self, some_value):
self.some_value = some_value
</code></pre>
<p><strong>someclient.py</strong></p>
<pre><code>class SomeClient:
def __init__(self, some_class_instance):
self.some_class_helper = some_class_instance
</code></pre>
<p>Here, the functionality of <code>SomeClient</code> clearly relies on <code>SomeClass</code> or at least something that behaves like it. However, someclient.py will work just fine without <code>import someclass</code>. Is this ok? It feels wrong to use something without saying anywhere that you're even using it.</p>
| 2 | 2009-10-12T20:35:36Z | 1,557,002 | <p>This is a good python code, "we are all consenting adults here", maybe if you expect a class you should include a comment and that's ok.</p>
| 1 | 2009-10-12T21:16:22Z | [
"python",
"coding-style"
] |
non-blocking read/log from an http stream | 1,557,175 | <p>I have a client that connects to an HTTP stream and logs the text data it consumes. </p>
<p>I send the streaming server an HTTP GET request... The server replies and continuously publishes data... It will either publish text or send a ping (text) message regularly... and will never close the connection.</p>
<p>I need to read and log the data it consumes in a non-blocking manner.</p>
<p>I am doing something like this:</p>
<pre><code>import urllib2
req = urllib2.urlopen(url)
for dat in req:
with open('out.txt', 'a') as f:
f.write(dat)
</code></pre>
<p>My questions are:<br>
will this ever block when the stream is continuous?<br>
how much data is read in each chunk and can it be specified/tuned?<br>
is this the best way to read/log an http stream?</p>
| 6 | 2009-10-12T21:59:39Z | 1,557,259 | <p>Hey, that's three questions in one! ;-)</p>
<p>It could block sometimes - even if your server is generating data quite quickly, network bottlenecks could in theory cause your reads to block.</p>
<p>Reading the URL data using "for dat in req" will mean reading a line at a time - not really useful if you're reading binary data such as an image. You get better control if you use</p>
<pre><code>chunk = req.read(size)
</code></pre>
<p>which can of course block.</p>
<p>Whether it's the best way depends on specifics not available in your question. For example, if you need to run with no blocking calls whatever, you'll need to consider a framework like <a href="http://twistedmatrix.com/">Twisted</a>. If you don't want blocking to hold you up and don't want to use Twisted (which is a whole new paradigm compared to the blocking way of doing things), then you can spin up a thread to do the reading and writing to file, while your main thread goes on its merry way:</p>
<pre><code>def func(req):
#code the read from URL stream and write to file here
...
t = threading.Thread(target=func)
t.start() # will execute func in a separate thread
...
t.join() # will wait for spawned thread to die
</code></pre>
<p>Obviously, I've omitted error checking/exception handling etc. but hopefully it's enough to give you the picture.</p>
| 6 | 2009-10-12T22:19:36Z | [
"python",
"http",
"logging",
"urllib2"
] |
non-blocking read/log from an http stream | 1,557,175 | <p>I have a client that connects to an HTTP stream and logs the text data it consumes. </p>
<p>I send the streaming server an HTTP GET request... The server replies and continuously publishes data... It will either publish text or send a ping (text) message regularly... and will never close the connection.</p>
<p>I need to read and log the data it consumes in a non-blocking manner.</p>
<p>I am doing something like this:</p>
<pre><code>import urllib2
req = urllib2.urlopen(url)
for dat in req:
with open('out.txt', 'a') as f:
f.write(dat)
</code></pre>
<p>My questions are:<br>
will this ever block when the stream is continuous?<br>
how much data is read in each chunk and can it be specified/tuned?<br>
is this the best way to read/log an http stream?</p>
| 6 | 2009-10-12T21:59:39Z | 1,557,380 | <p>Yes when you catch up with the server it will block until the server produces more data</p>
<p>Each dat will be one line including the newline on the end</p>
<p>twisted is a good option</p>
<p>I would swap the with and for around in your example, do you really want to open and close the file for every line that arrives?</p>
| 1 | 2009-10-12T22:52:05Z | [
"python",
"http",
"logging",
"urllib2"
] |
non-blocking read/log from an http stream | 1,557,175 | <p>I have a client that connects to an HTTP stream and logs the text data it consumes. </p>
<p>I send the streaming server an HTTP GET request... The server replies and continuously publishes data... It will either publish text or send a ping (text) message regularly... and will never close the connection.</p>
<p>I need to read and log the data it consumes in a non-blocking manner.</p>
<p>I am doing something like this:</p>
<pre><code>import urllib2
req = urllib2.urlopen(url)
for dat in req:
with open('out.txt', 'a') as f:
f.write(dat)
</code></pre>
<p>My questions are:<br>
will this ever block when the stream is continuous?<br>
how much data is read in each chunk and can it be specified/tuned?<br>
is this the best way to read/log an http stream?</p>
| 6 | 2009-10-12T21:59:39Z | 1,558,074 | <p>You're using too high-level an interface to have good control about such issues as blocking and buffering block sizes. If you're not willing to go all the way to an async interface (in which case <a href="http://twistedmatrix.com/trac/" rel="nofollow">twisted</a>, already suggested, is hard to beat!), why not <a href="http://docs.python.org/library/httplib.html" rel="nofollow">httplib</a>, which is after all in the standard library? HTTPResponse instance <code>.read(amount)</code> method is more likely to block for no longer than needed to read <code>amount</code> bytes, than the similar method on the object returned by <code>urlopen</code> (although admittedly there are no documented specs about that on either module, hmmm...). </p>
| 3 | 2009-10-13T03:34:29Z | [
"python",
"http",
"logging",
"urllib2"
] |
non-blocking read/log from an http stream | 1,557,175 | <p>I have a client that connects to an HTTP stream and logs the text data it consumes. </p>
<p>I send the streaming server an HTTP GET request... The server replies and continuously publishes data... It will either publish text or send a ping (text) message regularly... and will never close the connection.</p>
<p>I need to read and log the data it consumes in a non-blocking manner.</p>
<p>I am doing something like this:</p>
<pre><code>import urllib2
req = urllib2.urlopen(url)
for dat in req:
with open('out.txt', 'a') as f:
f.write(dat)
</code></pre>
<p>My questions are:<br>
will this ever block when the stream is continuous?<br>
how much data is read in each chunk and can it be specified/tuned?<br>
is this the best way to read/log an http stream?</p>
| 6 | 2009-10-12T21:59:39Z | 1,564,523 | <p>Another option is to use the <code>socket</code> module directly. Establish a connection, send the HTTP request, set the socket to non-blocking mode, and then read the data with <code>socket.recv()</code> handling 'Resource temporarily unavailable' exceptions (which means that there is nothing to read). A very rough example is this:</p>
<pre><code>import socket, time
BUFSIZE = 1024
s = socket.socket()
s.connect(('localhost', 1234))
s.send('GET /path HTTP/1.0\n\n')
s.setblocking(False)
running = True
while running:
try:
print "Attempting to read from socket..."
while True:
data = s.recv(BUFSIZE)
if len(data) == 0: # remote end closed
print "Remote end closed"
running = False
break
print "Received %d bytes: %r" % (len(data), data)
except socket.error, e:
if e[0] != 11: # Resource temporarily unavailable
print e
raise
# perform other program tasks
print "Sleeping..."
time.sleep(1)
</code></pre>
<p>However, <code>urllib.urlopen()</code> has some benefits if the web server redirects, you need URL based basic authentication etc. You could make use of the <code>select</code> module which will tell you when there is data to read.</p>
| 3 | 2009-10-14T06:13:33Z | [
"python",
"http",
"logging",
"urllib2"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 1,557,577 | <p>In Linux or UNIX:</p>
<pre><code>time python yourprogram.py
</code></pre>
<p>In Windows, see this Stackoverflow discussion: <a href="http://stackoverflow.com/questions/673523/how-to-measure-execution-time-of-command-in-windows-command-line">http://stackoverflow.com/questions/673523/how-to-measure-execution-time-of-command-in-windows-command-line</a></p>
| 66 | 2009-10-12T23:59:18Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 1,557,584 | <p>The simplest way in python:</p>
<pre><code>import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
</code></pre>
<p>This assumes that your program takes at least a tenth of second to run.</p>
<p>Prints:</p>
<pre><code>--- 0.764891862869 seconds ---
</code></pre>
| 514 | 2009-10-13T00:00:53Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 1,557,605 | <p>The solution of rogeriopvl works fine, but if you want more specific info you can use the python built-in profiler. Check this page:</p>
<p><a href="http://docs.python.org/library/profile.html">http://docs.python.org/library/profile.html</a></p>
<p>a profiler tells you a lot of useful information like the time spent in every function</p>
| 10 | 2009-10-13T00:07:58Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 1,557,805 | <pre><code>import time
start_time = time.clock()
main()
print time.clock() - start_time, "seconds"
</code></pre>
<p><code>time.clock()</code> returns the processor time, which allows us to calculate only the time used by this process (on Unix anyway). The documentation says "in any case, this is the function to use for benchmarking Python or timing algorithms"</p>
| 28 | 2009-10-13T01:25:01Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 1,557,906 | <p>I put this <code>timing.py</code> module into my own <code>site-packages</code> directory, and just insert <code>import timing</code> at the top of my module:</p>
<pre><code>import atexit
from time import clock
def secondsToStr(t):
return "%d:%02d:%02d.%03d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(t*1000,),1000,60,60])
line = "="*40
def log(s, elapsed=None):
print line
print secondsToStr(clock()), '-', s
if elapsed:
print "Elapsed time:", elapsed
print line
print
def endlog():
end = clock()
elapsed = end-start
log("End Program", secondsToStr(elapsed))
def now():
return secondsToStr(clock())
start = clock()
atexit.register(endlog)
log("Start Program")
</code></pre>
<p>I can also call <code>timing.log</code> from within my program if there are significant stages within the program I want to show. But just including <code>import timing</code> will print the start and end times, and overall elapsed time. (Forgive my obscure <code>secondsToStr</code> function, it just formats a floating point number of seconds to hh:mm:ss.sss form.)</p>
| 113 | 2009-10-13T02:08:22Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 1,558,436 | <p>Even better for Linux: <code>/usr/bin/time</code></p>
<pre><code>$ /usr/bin/time -v python rhtest2.py
Command being timed: "python rhtest2.py"
User time (seconds): 4.13
System time (seconds): 0.07
Percent of CPU this job got: 91%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:04.58
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 0
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 15
Minor (reclaiming a frame) page faults: 5095
Voluntary context switches: 27
Involuntary context switches: 279
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
</code></pre>
<p>Normally, just <code>time</code> is a simpler shell builtin that shadows the more capable <code>/usr/bin/time</code>.</p>
| 17 | 2009-10-13T06:10:50Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 12,344,609 | <p>I really like Paul McGuire's answer, but I use Python3. So for those who are interested: here's a modification of his answer that works with Python 3 on *nix (I imagine, under Windows, that clock() should be used instead of time()):</p>
<pre><code>#python3
import atexit
from time import time
from datetime import timedelta
def secondsToStr(t):
return str(timedelta(seconds=t))
line = "="*40
def log(s, elapsed=None):
print(line)
print(secondsToStr(time()), '-', s)
if elapsed:
print("Elapsed time:", elapsed)
print(line)
print()
def endlog():
end = time()
elapsed = end-start
log("End Program", secondsToStr(elapsed))
def now():
return secondsToStr(time())
start = time()
atexit.register(endlog)
log("Start Program")
</code></pre>
<p>If you find this useful, you should still up-vote his answer instead of this one, as he did most of the work ;).</p>
| 18 | 2012-09-10T02:03:40Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 20,874,769 | <p>You can use the python profiler cProfile to measure <a href="http://en.wikipedia.org/wiki/CPU_time">CPU time</a> and additionally how much time is spent inside each function and how many times each function is called. This is very useful if you want to improve performance of your script without knowing where to start. <a href="http://stackoverflow.com/a/582337/2073469">This answer</a> to another SO question is pretty good. It's always good to have a look in <a href="http://docs.python.org/2/library/profile.html">the docs</a> too.</p>
<p>Here's an example how to profile a script using cProfile from a command line:</p>
<pre><code>$ python -m cProfile euler048.py
1007 function calls in 0.061 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.061 0.061 <string>:1(<module>)
1000 0.051 0.000 0.051 0.000 euler048.py:2(<lambda>)
1 0.005 0.005 0.061 0.061 euler048.py:2(<module>)
1 0.000 0.000 0.061 0.061 {execfile}
1 0.002 0.002 0.053 0.053 {map}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler objects}
1 0.000 0.000 0.000 0.000 {range}
1 0.003 0.003 0.003 0.003 {sum}
</code></pre>
| 23 | 2014-01-02T00:35:57Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 26,099,345 | <p>I like the output the <code>datetime</code> module provides, where time delta objects show days, hours, minutes etc. as necessary in a human-readable way.</p>
<p>For example:</p>
<pre><code>from datetime import datetime
start_time = datetime.now()
# do your work here
end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time))
</code></pre>
<p>Sample output e.g.</p>
<pre><code>Duration: 0:00:08.309267
</code></pre>
<p>or</p>
<pre><code>Duration: 1 day, 1:51:24.269711
</code></pre>
<p><strong>Update:</strong> As J.F. Sebastian mentioned, this approach might encounter some tricky cases with local time, so it's safer to use:</p>
<pre><code>import time
from datetime import timedelta
start_time = time.monotonic()
end_time = time.monotonic()
print(timedelta(seconds=end_time - start_time))
</code></pre>
| 16 | 2014-09-29T11:55:08Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 26,468,682 | <p>There is a <code>timeit</code> module which can be used to time the execution times of python codes.
It has detailed documentation and examples in python docs (<a href="https://docs.python.org/2/library/timeit.html" rel="nofollow">https://docs.python.org/2/library/timeit.html</a>)</p>
| 3 | 2014-10-20T14:55:51Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 28,218,696 | <p>I like Paul McGuire's answer too and came up with a context manager form which suited more my needs.</p>
<pre><code>import datetime as dt
import timeit
class TimingManager(object):
"""Context Manager used with the statement 'with' to time some execution.
Example:
with TimingManager() as t:
# Code to time
"""
clock = timeit.default_timer
def __enter__(self):
"""
"""
self.start = self.clock()
self.log('\n=> Start Timing: {}')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""
"""
self.endlog()
return False
def log(self, s, elapsed=None):
"""Log current time and elapsed time if present.
:param s: Text to display, use '{}' to format the text with
the current time.
:param elapsed: Elapsed time to display. Dafault: None, no display.
"""
print s.format(self._secondsToStr(self.clock()))
if(elapsed is not None):
print 'Elapsed time: {}\n'.format(elapsed)
def endlog(self):
"""Log time for the end of execution with elapsed time.
"""
self.log('=> End Timing: {}', self.now())
def now(self):
"""Return current elapsed time as hh:mm:ss string.
:return: String.
"""
return str(dt.timedelta(seconds = self.clock() - self.start))
def _secondsToStr(self, sec):
"""Convert timestamp to h:mm:ss string.
:param sec: Timestamp.
"""
return str(dt.datetime.fromtimestamp(sec))
</code></pre>
| 3 | 2015-01-29T15:42:24Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 28,827,752 | <blockquote>
<p>I've looked at the timeit module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
</blockquote>
<pre><code>$ python -mtimeit -n1 -r1 -t -s "from your_module import main" "main()"
</code></pre>
<p>It runs <code>your_module.main()</code> function one time and print the elapsed time using <code>time.time()</code> function as a timer.</p>
<p>To emulate <code>/usr/bin/time</code> in Python see <a href="http://stackoverflow.com/a/28521323/4279">Python subprocess with /usr/bin/time: how to capture timing info but ignore all other output?</a>.</p>
<p>To measure CPU time (e.g., don't include time during <code>time.sleep()</code>) for each function, you could use <code>profile</code> module (<code>cProfile</code> on Python 2):</p>
<pre><code>$ python3 -mprofile your_module.py
</code></pre>
<p>You could pass <code>-p</code> to <code>timeit</code> command above if you want to use the same timer as <code>profile</code> module uses.</p>
<p>See <a href="http://stackoverflow.com/q/582336/4279">How can you profile a Python script?</a></p>
| 5 | 2015-03-03T09:04:52Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 29,503,779 | <p>This is Paul McGuire's answer that works for me. Just in case someone was having trouble running that one. </p>
<pre><code>import atexit
from time import clock
def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
value = next(it)
else:
value = initializer
for element in it:
value = function(value, element)
return value
def secondsToStr(t):
return "%d:%02d:%02d.%03d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(t*1000,),1000,60,60])
line = "="*40
def log(s, elapsed=None):
print (line)
print (secondsToStr(clock()), '-', s)
if elapsed:
print ("Elapsed time:", elapsed)
print (line)
def endlog():
end = clock()
elapsed = end-start
log("End Program", secondsToStr(elapsed))
def now():
return secondsToStr(clock())
def main():
start = clock()
atexit.register(endlog)
log("Start Program")
</code></pre>
<p>call <code>timing.main()</code> from your program after importing the file.</p>
| 1 | 2015-04-08T00:24:28Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 30,352,928 | <p>Ipython "timeit" any script: </p>
<pre><code>def foo():
%run bar.py
timeit foo()
</code></pre>
| 4 | 2015-05-20T14:40:36Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 36,444,633 | <pre><code>from time import time
start_time = time()
...
end_time = time()
time_taken = end_time - start_time # time_taken is in seconds
hours, rest = divmod(time_taken,3600)
minutes, seconds = divmod(rest, 60)
</code></pre>
| 6 | 2016-04-06T07:45:50Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 37,289,957 | <p><strong>time.clock()</strong></p>
<blockquote>
<p>Deprecated since version 3.3: The behavior of this function depends
on the platform: use <strong><em>perf_counter()</em></strong> or <strong><em>process_time()</em></strong> instead,
depending on your requirements, to have a well-defined behavior.</p>
</blockquote>
<p><strong>time.perf_counter()</strong></p>
<blockquote>
<p>Return the value (in fractional seconds) of a performance counter,
i.e. a clock with the highest available resolution to measure a short
duration. It <strong><em>does</em></strong> include time elapsed during sleep and is
system-wide.</p>
</blockquote>
<p><strong>time.process_time()</strong></p>
<blockquote>
<p>Return the value (in fractional seconds) of the sum of the system and
user CPU time of the current process. It <strong><em>does not</em></strong> include time elapsed
during sleep.</p>
</blockquote>
<pre><code>start = time.process_time()
... do something
elapsed = (time.process_time() - start)
</code></pre>
| 2 | 2016-05-18T03:49:41Z | [
"python",
"time"
] |
How to get time of a python program execution? | 1,557,571 | <p>I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.</p>
<p>I've looked at the <code>timeit</code> module, but it seems it's only for small snippets of code. I want to time the whole program.</p>
| 292 | 2009-10-12T23:56:47Z | 38,154,549 | <p>The following snippet prints elapsed time in nice human readable <code><HH:MM:SS></code> format.</p>
<pre><code>import time
from datetime import timedelta
start_time = time.time()
#
# Perform lots of computations.
#
elapsed_time_secs = time.time() - start_time
print "Execution took: %s secs (Wall clock time)" % timedelta(seconds=round(elapsed_time_secs))
</code></pre>
| 1 | 2016-07-01T22:24:32Z | [
"python",
"time"
] |
PIL vs Python-GD for crop and resize | 1,557,625 | <p>I am creating custom images that I later convert to an image pyramid for Seadragon AJAX. The images and image pyramid are created using PIL. It currently take a few hours to generate the images and image pyramid for approximately 100 pictures that have a combined width and height of about 32,000,000 by 1000 (yes, the image is very long and narrow). The performance is roughly similar another algorithm I have tried (i.e. <a href="http://github.com/openzoom/deepzoom.py" rel="nofollow">deepzoom.py</a>). I plan to see if python-gd would perform better due to most of its functionality being coded in C (from the GD library). I would assume a significant performance increase however I am curious to hear the opinion of others. In particular the resizing and cropping is slow in PIL (w/ Image.ANTIALIAS). Will this improve considerable if I use Python-GD?</p>
<p>Thanks in advance for the comments and suggestions.</p>
<p>EDIT: The performance difference between PIL and python-GD seems minimal. I will refactor my code to reduce performance bottlenecks and include support for multiple processors. I've tested out the python 'multiprocessing' module. Results are encouraging.</p>
| 2 | 2009-10-13T00:13:21Z | 1,557,796 | <p>PIL is mostly in C.</p>
<p>Antialiasing is slow. When you turn off antialiasing, what happens to the speed?</p>
| 1 | 2009-10-13T01:22:18Z | [
"python",
"ajax",
"gd",
"python-imaging-library",
"seadragon"
] |
PIL vs Python-GD for crop and resize | 1,557,625 | <p>I am creating custom images that I later convert to an image pyramid for Seadragon AJAX. The images and image pyramid are created using PIL. It currently take a few hours to generate the images and image pyramid for approximately 100 pictures that have a combined width and height of about 32,000,000 by 1000 (yes, the image is very long and narrow). The performance is roughly similar another algorithm I have tried (i.e. <a href="http://github.com/openzoom/deepzoom.py" rel="nofollow">deepzoom.py</a>). I plan to see if python-gd would perform better due to most of its functionality being coded in C (from the GD library). I would assume a significant performance increase however I am curious to hear the opinion of others. In particular the resizing and cropping is slow in PIL (w/ Image.ANTIALIAS). Will this improve considerable if I use Python-GD?</p>
<p>Thanks in advance for the comments and suggestions.</p>
<p>EDIT: The performance difference between PIL and python-GD seems minimal. I will refactor my code to reduce performance bottlenecks and include support for multiple processors. I've tested out the python 'multiprocessing' module. Results are encouraging.</p>
| 2 | 2009-10-13T00:13:21Z | 28,585,418 | <p>VIPS includes a <a href="http://libvips.blogspot.co.uk/2013/03/making-deepzoom-zoomify-and-google-maps.html" rel="nofollow">fast deepzoom creator</a>. I timed <code>deepzoom.py</code> and on my machine I see:</p>
<pre><code>$ time ./wtc.py
real 0m29.601s
user 0m29.158s
sys 0m0.408s
peak RES 450mb
</code></pre>
<p>where <code>wtc.jpg</code> is a 10,000 x 10,000 pixel RGB JPG image, and <code>wtc.py</code> is using <a href="https://github.com/openzoom/deepzoom.py/blob/develop/examples/helloworld/helloworld.py" rel="nofollow">these settings</a>. </p>
<p>VIPS is around three times faster and needs a quarter of the memory:</p>
<pre><code>$ time vips dzsave wtc.jpg wtc --overlap 2 --tile-size 128 --suffix .png[compression=0]
real 0m10.819s
user 0m37.084s
sys 0m15.314s
peak RES 100mb
</code></pre>
<p>I'm not sure why sys is so much higher. </p>
| 0 | 2015-02-18T13:57:01Z | [
"python",
"ajax",
"gd",
"python-imaging-library",
"seadragon"
] |
How to make complex contains queries in Django? | 1,557,850 | <p>I need to make query like this: </p>
<blockquote>
<p>WHERE Comment like '%ev% 3628%' or Comment like '%ew% 3628%'</p>
</blockquote>
<p>the number '3628' is a parametr. So I've tried in my view: </p>
<p><strong>First try:</strong> </p>
<pre><code>wherestr = "Comment like '%%ev%% %s%%' or Comment like '%%ew%% %s%%'" % (rev_number, rev_number)
comment_o = Issuecomments.objects.extra(where=[wherestr])
</code></pre>
<p><strong>but I've got:</strong><br />
TypeError at /comments_by_rev/3628/</p>
<p>not enough arguments for format string</p>
<p>Request Method: GET
Request URL: <a href="http://127.0.0.1:8001/comments%5Fby%5Frev/3628/" rel="nofollow">http://127.0.0.1:8001/comments%5Fby%5Frev/3628/</a>
Exception Type: TypeError
Exception Value: </p>
<p>not enough arguments for format string</p>
<p><strong>Second try:</strong> </p>
<pre><code>comment = IssuetrackerIssuecomments.objects.filter(Q(comment__contains=rev_number), Q(comment__contains='ew') | Q(comment__contains='ev'))
</code></pre>
<p>but its not excactly the same.<br />
Have you people of wisdom any idea how to accomplish this?</p>
| 1 | 2009-10-13T01:43:28Z | 1,557,872 | <p>You need something similar to this:</p>
<pre><code>from django.db.models import Q
def myview(request):
query = "hi" #string to search for
items = self.filter(Q(comment__contains=query) | Q(comment__contains=query))
...
</code></pre>
<p>Just make sure the query string is properly escaped.</p>
| 1 | 2009-10-13T01:52:20Z | [
"python",
"django"
] |
How to make complex contains queries in Django? | 1,557,850 | <p>I need to make query like this: </p>
<blockquote>
<p>WHERE Comment like '%ev% 3628%' or Comment like '%ew% 3628%'</p>
</blockquote>
<p>the number '3628' is a parametr. So I've tried in my view: </p>
<p><strong>First try:</strong> </p>
<pre><code>wherestr = "Comment like '%%ev%% %s%%' or Comment like '%%ew%% %s%%'" % (rev_number, rev_number)
comment_o = Issuecomments.objects.extra(where=[wherestr])
</code></pre>
<p><strong>but I've got:</strong><br />
TypeError at /comments_by_rev/3628/</p>
<p>not enough arguments for format string</p>
<p>Request Method: GET
Request URL: <a href="http://127.0.0.1:8001/comments%5Fby%5Frev/3628/" rel="nofollow">http://127.0.0.1:8001/comments%5Fby%5Frev/3628/</a>
Exception Type: TypeError
Exception Value: </p>
<p>not enough arguments for format string</p>
<p><strong>Second try:</strong> </p>
<pre><code>comment = IssuetrackerIssuecomments.objects.filter(Q(comment__contains=rev_number), Q(comment__contains='ew') | Q(comment__contains='ev'))
</code></pre>
<p>but its not excactly the same.<br />
Have you people of wisdom any idea how to accomplish this?</p>
| 1 | 2009-10-13T01:43:28Z | 1,557,873 | <p>Take a look at <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/querysets/</a>, specifically</p>
<p>icontains: Case-insensitive containment test.</p>
<p>Example: Entry.objects.get(headline__icontains='Lennon')</p>
<p>SQL equivalent: SELECT ... WHERE headline ILIKE '%Lennon%';</p>
<p>Since you're looking for a pattern like %%ev%% or %%ew%%, consider the IREGEX or REGEX versions as well?</p>
<p>Lastly, consider performing the search differently...perhaps parse out the interesting parts of the message and put them in their own indexed columns for querying later. You'll regret doing this search once the table gets large:).</p>
| 0 | 2009-10-13T01:52:43Z | [
"python",
"django"
] |
How to make complex contains queries in Django? | 1,557,850 | <p>I need to make query like this: </p>
<blockquote>
<p>WHERE Comment like '%ev% 3628%' or Comment like '%ew% 3628%'</p>
</blockquote>
<p>the number '3628' is a parametr. So I've tried in my view: </p>
<p><strong>First try:</strong> </p>
<pre><code>wherestr = "Comment like '%%ev%% %s%%' or Comment like '%%ew%% %s%%'" % (rev_number, rev_number)
comment_o = Issuecomments.objects.extra(where=[wherestr])
</code></pre>
<p><strong>but I've got:</strong><br />
TypeError at /comments_by_rev/3628/</p>
<p>not enough arguments for format string</p>
<p>Request Method: GET
Request URL: <a href="http://127.0.0.1:8001/comments%5Fby%5Frev/3628/" rel="nofollow">http://127.0.0.1:8001/comments%5Fby%5Frev/3628/</a>
Exception Type: TypeError
Exception Value: </p>
<p>not enough arguments for format string</p>
<p><strong>Second try:</strong> </p>
<pre><code>comment = IssuetrackerIssuecomments.objects.filter(Q(comment__contains=rev_number), Q(comment__contains='ew') | Q(comment__contains='ev'))
</code></pre>
<p>but its not excactly the same.<br />
Have you people of wisdom any idea how to accomplish this?</p>
| 1 | 2009-10-13T01:43:28Z | 1,562,711 | <p>You almost got it right... The problem is that your % are being subsituted twice. <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none" rel="nofollow">Django actually has a way of passing parameters in the extra clause</a> like this</p>
<pre><code>wherestr = "Comment like '%%ev%% %s%%' or Comment like '%%ew%% %s%%'"
params = (rev_number, rev_number)
comment_o = Issuecomments.objects.extra(where=[wherestr], params=[params])
</code></pre>
<p>This is a better way of passing the parameters as it won't leave you open to SQL injection attacks like your way will.</p>
| 0 | 2009-10-13T20:24:55Z | [
"python",
"django"
] |
PyQt: Displaying QTextEdits over the window | 1,557,864 | <p>I want to display some QTextEdits over my main window at arbitrary locations. Below is my first attempt. It doesn't quite work. If I create the text edits before I show the window, the text edits appear, but if I create them after I have shown the window they don't appear. What's up with that? How can I get the ones created later to show up?</p>
<pre><code>import sys, random
from PyQt4 import QtGui, QtCore
app = QtGui.QApplication(sys.argv)
win = QtGui.QMainWindow()
win.resize(500,500)
def new_text():
print "new text"
text = QtGui.QTextEdit(win)
text.move(random.random() * 400, random.random() * 400)
for i in range(3):
new_text()
timer = QtCore.QTimer()
timer.connect(timer, QtCore.SIGNAL("timeout()"), new_text)
timer.start(500)
win.show()
app.exec_()
</code></pre>
| 1 | 2009-10-13T01:49:50Z | 1,557,946 | <p>Oh, I got it. You have to call show on each widget before it appears. I guess QMainWindow.show recursively calls the method for all of its children. So just add text.show() to the end of the new_text function and it works.</p>
| 1 | 2009-10-13T02:32:08Z | [
"python",
"qt",
"qt4",
"pyqt",
"pyqt4"
] |
Getting multiple properties at the same time in Appscript | 1,557,910 | <p>I am using <a href="http://appscript.sourceforge.net/" rel="nofollow">Appscript</a> - a Python interface to AppleScript - in a project of mine that basically gets data from <a href="http://culturedcode.com/things/" rel="nofollow">a Mac application</a>.</p>
<p>Here is a sample code:</p>
<pre><code> asobj = app('Things').to_dos()[0]
self.id = asobj.id()
self.name = asobj.name()
self.status = asobj.status()
</code></pre>
<p>Every invocation of the properties (id, name, status) does inter-process call and hence it is slow .. especially when you do the same for thousands of the objects.</p>
<p>Is there a way to get multiple properties at the same time via AppleScript's Python interface (appscript)?</p>
| 1 | 2009-10-13T02:09:27Z | 1,558,045 | <p>I'm not 100% sure how this would be expressed in Python, but most Applescript objects support a "properties" property which will return a dictionary containing key/value pairs for each of the supported properties of that object. I'm guessing that calling <code>asobj.properties()</code> would return an appropriate data structure from which you can then retrieve any individual properties you want.</p>
| 3 | 2009-10-13T03:16:28Z | [
"python",
"osx",
"applescript",
"appscript"
] |
Getting multiple properties at the same time in Appscript | 1,557,910 | <p>I am using <a href="http://appscript.sourceforge.net/" rel="nofollow">Appscript</a> - a Python interface to AppleScript - in a project of mine that basically gets data from <a href="http://culturedcode.com/things/" rel="nofollow">a Mac application</a>.</p>
<p>Here is a sample code:</p>
<pre><code> asobj = app('Things').to_dos()[0]
self.id = asobj.id()
self.name = asobj.name()
self.status = asobj.status()
</code></pre>
<p>Every invocation of the properties (id, name, status) does inter-process call and hence it is slow .. especially when you do the same for thousands of the objects.</p>
<p>Is there a way to get multiple properties at the same time via AppleScript's Python interface (appscript)?</p>
| 1 | 2009-10-13T02:09:27Z | 1,565,728 | <p>If you have a large number of elements, it will be quicker to grab your properties like this:</p>
<pre><code>ref = app('Things').to_dos
ids = ref.id()
names = ref.name()
statuses = ref.status()
</code></pre>
<p>and then use Python's zip() function to rearrange them as needed. The appscript documentation has a chapter on optimisation techniques that explains this in more detail.</p>
<p>You should also grab copies of the ASDictionary and ASTranslate tools from the appscript website if you've not already done so. ASTranslate will help you convert application commands from AppleScript to appscript syntax. ASDictionary will export application dictionaries in appscript-style format and also enables appscript's built-in help() method, allowing you to explore application dictionaries interactively (much more powerful than dir()).</p>
| 0 | 2009-10-14T11:35:29Z | [
"python",
"osx",
"applescript",
"appscript"
] |
Install custom modules in a python virtual enviroment | 1,557,972 | <p>I am doing some pylons work in a virtual python enviorment, I want to use MySQL with SQLalchemy but I can't install the MySQLdb module on my virtual enviorment, I can't use easyinstall because I am using a version that was compiled for python 2.6 in a .exe format, I tried running the install from inside the virtual enviorment but that did not work, any sugestions?</p>
| 0 | 2009-10-13T02:43:26Z | 1,563,869 | <p>Ok Got it all figured out, After I installed the module on my normal python 2.6 install I went into my Python26 folder and low and behold I happened to find a file called MySQL-python-wininst which happened to be a list of all of the installed module files. Basicly it was two folders called MySQLdb and another called MySQL_python-1.2.2-py2.6.egg-info as well as three other files: _mysql.pyd, _mysql_exceptions.py, _mysql_exceptions.pyc. So I went into the folder where they were located (Python26/Lib/site-packages) and copied them to virtualenv's site-packages folder (env/Lib/site-packages) and the module was fully functional!</p>
<p>Note: All paths are the defaults</p>
| 0 | 2009-10-14T01:49:43Z | [
"python",
"mysql",
"pylons",
"module",
"virtualenv"
] |
relevant query to what is the best python method for encryption | 1,558,287 | <p>I tried to use the gnupg.py module encryption decryption function named<br>
" def test_encryption_and_decryption(self): "</p>
<p>Could i use this function by passing the key or fingerprint retrieved from public key server.</p>
<p>I am getting the key by this :</p>
<pre><code>retk = urllib.urlopen('http://pool.sks-keyservers.net:11371/pks/lookup
op=get&search=hex format of key')
pub_key = retk.read()
</code></pre>
<p>i also tried to pass the fingerprint in encrypt method :</p>
<pre><code>data = "Hello, world!"
edata = str(self.gpg.encrypt(data, fingerprint))
print edata
</code></pre>
<p>Not getting the way how to do .Is somebody help me out by giving their valuble and effective solution/suggestions.</p>
<p>thanks!</p>
| 1 | 2009-10-13T05:09:01Z | 1,558,417 | <p>Before you can encrypt with a key whose keyid you have, you need to import the key into the keyring. Use the <code>import_keys</code> function for that.</p>
<p><strong>Edit</strong>: that you cannot encrypt even after importing the key is because GPG does not trust it. This becomes apparent when you turn on verbose messages; you'll get</p>
<pre><code>gpg: <keyid>: There is no assurance this key belongs to the named user
</code></pre>
<p>To work around (short of setting up a trust path for the key), you can change gpg's trust model. The following program works for me (with my key as an example)</p>
<pre><code>import gnupg, urllib
retk = urllib.urlopen("http://keyserver.pramberger.at/pks/"
"lookup?op=get&search=0x6AF053F07D9DC8D2")
pub_key = retk.read()
gpg = gnupg.GPG(gnupghome="/tmp/foo", verbose=True)
print "Import:", gpg.import_keys(pub_key).summary()
print "Encrypt:", gpg.encrypt("Hello, world!", "6AF053F07D9DC8D2",
always_trust=True)
</code></pre>
| 2 | 2009-10-13T06:01:07Z | [
"python",
"encryption"
] |
How can I distribute python programs? | 1,558,385 | <p>My application looks like this:</p>
<pre>
main.py
windows/
__init__.py
mainwindow.py
...
model/
__init__.py
orders.py
...
resources/
image1.png
logo.jpg
...
</pre>
<p>The program is started with main.py. Is there a good way to create a 'final' application out of it? I'm thinking of something like py2exe/py2app, but without copying the python interpreter / modules into the application where one has only one executable.</p>
<p>I had a look at distutils, but this looks like it installs a program into the Python directory, which isn't usual on non-linux platforms.</p>
<p>At the moment I just copy the whole source folder onto the target machine and create an alias to <code>main.pyw</code> on windows. Some inconveniences:</p>
<ul>
<li>The icon is the default python icon.</li>
<li>I have to create the alias manually.</li>
<li>In my source directory there are a lot of additional files like the source control folder.</li>
<li>I have to rename <code>main.py</code> to <code>main.pyw</code> manually.</li>
<li>It would be nice if only `.pyo* files are on the target machine. There's no real reason for it, I just don't like having unnecessary files.</li>
</ul>
<p>How does one create a nice automated distribution?</p>
<ul>
<li>for windows? (That's the only platform that I have to support at the moment.)</li>
<li>for mac?</li>
<li>for linux?</li>
</ul>
| 61 | 2009-10-13T05:48:20Z | 1,558,404 | <p>The normal way of distributing Python applications is with <a href="http://docs.python.org/distutils/index.html">distutils</a>. It's made both for distributing library type python modules, and python applications, although I don't know how it works on Windows. You would on Windows have to install Python separately if you use distutils, in any case.</p>
<p>I'd probably recommend that you distribute it with disutils for Linux, and Py2exe or something similar for Windows. For OS X I don't know. If it's an end user application you would probably want an disk image type of thing, I don't know how to do that. But read <a href="http://limi.net/articles/firefox-mac-installation-experience-revisited/">this post</a> for more information on the user experience of it. For an application made for programmers you are probably OK with a distutils type install on OS X too.</p>
| 22 | 2009-10-13T05:54:46Z | [
"python",
"distribution"
] |
How can I distribute python programs? | 1,558,385 | <p>My application looks like this:</p>
<pre>
main.py
windows/
__init__.py
mainwindow.py
...
model/
__init__.py
orders.py
...
resources/
image1.png
logo.jpg
...
</pre>
<p>The program is started with main.py. Is there a good way to create a 'final' application out of it? I'm thinking of something like py2exe/py2app, but without copying the python interpreter / modules into the application where one has only one executable.</p>
<p>I had a look at distutils, but this looks like it installs a program into the Python directory, which isn't usual on non-linux platforms.</p>
<p>At the moment I just copy the whole source folder onto the target machine and create an alias to <code>main.pyw</code> on windows. Some inconveniences:</p>
<ul>
<li>The icon is the default python icon.</li>
<li>I have to create the alias manually.</li>
<li>In my source directory there are a lot of additional files like the source control folder.</li>
<li>I have to rename <code>main.py</code> to <code>main.pyw</code> manually.</li>
<li>It would be nice if only `.pyo* files are on the target machine. There's no real reason for it, I just don't like having unnecessary files.</li>
</ul>
<p>How does one create a nice automated distribution?</p>
<ul>
<li>for windows? (That's the only platform that I have to support at the moment.)</li>
<li>for mac?</li>
<li>for linux?</li>
</ul>
| 61 | 2009-10-13T05:48:20Z | 1,558,439 | <p>If you are distributing on windows, use an <a href="http://www.installshield.com" rel="nofollow">installer</a> to install all the relevant files/interpeter whatever is needed. Distribute a setup.exe. That is the best way on windows. Otherwise users will complain.</p>
| 1 | 2009-10-13T06:11:21Z | [
"python",
"distribution"
] |
How can I distribute python programs? | 1,558,385 | <p>My application looks like this:</p>
<pre>
main.py
windows/
__init__.py
mainwindow.py
...
model/
__init__.py
orders.py
...
resources/
image1.png
logo.jpg
...
</pre>
<p>The program is started with main.py. Is there a good way to create a 'final' application out of it? I'm thinking of something like py2exe/py2app, but without copying the python interpreter / modules into the application where one has only one executable.</p>
<p>I had a look at distutils, but this looks like it installs a program into the Python directory, which isn't usual on non-linux platforms.</p>
<p>At the moment I just copy the whole source folder onto the target machine and create an alias to <code>main.pyw</code> on windows. Some inconveniences:</p>
<ul>
<li>The icon is the default python icon.</li>
<li>I have to create the alias manually.</li>
<li>In my source directory there are a lot of additional files like the source control folder.</li>
<li>I have to rename <code>main.py</code> to <code>main.pyw</code> manually.</li>
<li>It would be nice if only `.pyo* files are on the target machine. There's no real reason for it, I just don't like having unnecessary files.</li>
</ul>
<p>How does one create a nice automated distribution?</p>
<ul>
<li>for windows? (That's the only platform that I have to support at the moment.)</li>
<li>for mac?</li>
<li>for linux?</li>
</ul>
| 61 | 2009-10-13T05:48:20Z | 1,558,488 | <p>I highly recommend <a href="http://www.pyinstaller.org/">Pyinstaller</a>, which supports all major platforms pretty seamlessly. Like py2exe and py2app, it produces a standard executable on Windows and an app bundle on OS X, but has the benefit of also doing a fantastic job of auto-resolving common dependencies and including them without extra configuration tweaks.</p>
<p>Also note that if you're deploying Python 2.6 to Windows, you should apply <a href="http://www.pyinstaller.org/ticket/39">this patch</a> to Pyinstaller trunk.</p>
<p>You indicated that you don't need an installer, but <a href="http://www.jrsoftware.org/isinfo.php">Inno Setup</a> is an easy to use and quick to setup choice for the Windows platform.</p>
| 40 | 2009-10-13T06:31:20Z | [
"python",
"distribution"
] |
How can I distribute python programs? | 1,558,385 | <p>My application looks like this:</p>
<pre>
main.py
windows/
__init__.py
mainwindow.py
...
model/
__init__.py
orders.py
...
resources/
image1.png
logo.jpg
...
</pre>
<p>The program is started with main.py. Is there a good way to create a 'final' application out of it? I'm thinking of something like py2exe/py2app, but without copying the python interpreter / modules into the application where one has only one executable.</p>
<p>I had a look at distutils, but this looks like it installs a program into the Python directory, which isn't usual on non-linux platforms.</p>
<p>At the moment I just copy the whole source folder onto the target machine and create an alias to <code>main.pyw</code> on windows. Some inconveniences:</p>
<ul>
<li>The icon is the default python icon.</li>
<li>I have to create the alias manually.</li>
<li>In my source directory there are a lot of additional files like the source control folder.</li>
<li>I have to rename <code>main.py</code> to <code>main.pyw</code> manually.</li>
<li>It would be nice if only `.pyo* files are on the target machine. There's no real reason for it, I just don't like having unnecessary files.</li>
</ul>
<p>How does one create a nice automated distribution?</p>
<ul>
<li>for windows? (That's the only platform that I have to support at the moment.)</li>
<li>for mac?</li>
<li>for linux?</li>
</ul>
| 61 | 2009-10-13T05:48:20Z | 1,558,580 | <p>Fredrik Lundh's <a href="http://effbot.org/zone/squeeze.htm" rel="nofollow"><code>squeeze.py</code></a> can create a single file that does not contain the Python interpreter, but instead contains bytecode. With the right arguments, you can include other files, modules, etc. in the result file. I used it successfully in one project. The resulting program ran on OS X, Linux and Windows without any problem!</p>
<p><strong>PS</strong>: Each machine needs to have a Python interpreter which is compatible with the bytecode generated by squeeze.py. You can generate different bytecode versions for different versions of Python, if need be (just run squeeze.py with the right version of Python).</p>
| 4 | 2009-10-13T07:02:05Z | [
"python",
"distribution"
] |
How can I distribute python programs? | 1,558,385 | <p>My application looks like this:</p>
<pre>
main.py
windows/
__init__.py
mainwindow.py
...
model/
__init__.py
orders.py
...
resources/
image1.png
logo.jpg
...
</pre>
<p>The program is started with main.py. Is there a good way to create a 'final' application out of it? I'm thinking of something like py2exe/py2app, but without copying the python interpreter / modules into the application where one has only one executable.</p>
<p>I had a look at distutils, but this looks like it installs a program into the Python directory, which isn't usual on non-linux platforms.</p>
<p>At the moment I just copy the whole source folder onto the target machine and create an alias to <code>main.pyw</code> on windows. Some inconveniences:</p>
<ul>
<li>The icon is the default python icon.</li>
<li>I have to create the alias manually.</li>
<li>In my source directory there are a lot of additional files like the source control folder.</li>
<li>I have to rename <code>main.py</code> to <code>main.pyw</code> manually.</li>
<li>It would be nice if only `.pyo* files are on the target machine. There's no real reason for it, I just don't like having unnecessary files.</li>
</ul>
<p>How does one create a nice automated distribution?</p>
<ul>
<li>for windows? (That's the only platform that I have to support at the moment.)</li>
<li>for mac?</li>
<li>for linux?</li>
</ul>
| 61 | 2009-10-13T05:48:20Z | 16,782,573 | <p>I may be mistaken, but doesn't IronPython have a built in compiler for windows?</p>
<p><a href="http://www.ironpython.net" rel="nofollow">http://www.ironpython.net</a></p>
<p>[EDIT]</p>
<p>Try out Cx_Freeze, By far the best .py to .exe (plus a few .dlls) compiler I've ever used.</p>
<p><a href="http://cx-freeze.sourceforge.net/" rel="nofollow">http://cx-freeze.sourceforge.net/</a> </p>
| 1 | 2013-05-28T01:29:48Z | [
"python",
"distribution"
] |
how do I get only the time in models | 1,558,896 | <p>How do I format datetime to give me only the time in my model</p>
| 2 | 2009-10-13T08:28:41Z | 1,558,940 | <p>If you've got a <code>datetime</code> object in your template called <code>foo</code>, use:</p>
<pre><code>{{ foo|time:"H:i" }}
</code></pre>
<p>Look at the <code>time</code> filter <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#time" rel="nofollow">documentation</a>. You're not limited to <code>"H:i"</code>, there are lots of options around for formatting <code>datetime</code> objects.</p>
<p>If for some reason you're wanting to do this directly in your model (which is <em>probably</em> not where it belongs), then use <code>datetime</code>'s <code>strftime</code> - take a look at the relevant <a href="http://docs.python.org/library/datetime.html#strftime-behavior" rel="nofollow">documentation</a>.</p>
<p>For example, again assuming a <code>datetime</code> object called <code>foo</code>:</p>
<pre><code>hour = foo.strftime("%H:%M")
</code></pre>
| 7 | 2009-10-13T08:37:56Z | [
"python",
"django"
] |
Convert from hex string to unicode | 1,559,065 | <p>How can i convert the <code>'dead'</code> string to an unicode string <code>u'\xde\xad'</code>?</p>
<p>Doing this:</p>
<pre><code>from binascii import unhexlify
out = ''.join(x for x in [unhexlify('de'), unhexlify('ad')])
</code></pre>
<p>creates a <code><type 'str'></code> string <code>'\xde\xad'</code></p>
<p>Trying to use the Unicode.join() like this:</p>
<pre><code>from binascii import unhexlify
out = ''.join(x for x in [u'', unhexlify('de'), unhexlify('ad')])
</code></pre>
<p>results in an error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xde in position 0: ordinal not in range(128)
</code></pre>
| 2 | 2009-10-13T09:09:16Z | 1,559,094 | <p>See <a href="http://www.amk.ca/python/howto/unicode" rel="nofollow">this Python unicode how-to</a>, and use something akin to:</p>
<pre><code>unicode('\x80abc', errors='replace')
</code></pre>
<p>or</p>
<pre><code>unicode('\x80abc', errors='ignore')
</code></pre>
| 1 | 2009-10-13T09:17:59Z | [
"python",
"unicode",
"utf-8",
"encode",
"decode"
] |
Convert from hex string to unicode | 1,559,065 | <p>How can i convert the <code>'dead'</code> string to an unicode string <code>u'\xde\xad'</code>?</p>
<p>Doing this:</p>
<pre><code>from binascii import unhexlify
out = ''.join(x for x in [unhexlify('de'), unhexlify('ad')])
</code></pre>
<p>creates a <code><type 'str'></code> string <code>'\xde\xad'</code></p>
<p>Trying to use the Unicode.join() like this:</p>
<pre><code>from binascii import unhexlify
out = ''.join(x for x in [u'', unhexlify('de'), unhexlify('ad')])
</code></pre>
<p>results in an error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xde in position 0: ordinal not in range(128)
</code></pre>
| 2 | 2009-10-13T09:09:16Z | 1,559,100 | <p>Unicode is designed to be compatible with Latin-1, you can use that and simply decode the bytestring:</p>
<pre><code>In [2]: unhexlify('dead').decode('latin1')
Out[2]: u'\xde\xad'
</code></pre>
| 5 | 2009-10-13T09:18:49Z | [
"python",
"unicode",
"utf-8",
"encode",
"decode"
] |
How do i use perspective projection in this library | 1,559,083 | <p>i found a library called <a href="http://code.google.com/p/pyeuclid/" rel="nofollow">pyeuclid</a> and it <a href="http://partiallydisassembled.net/euclid/index.html" rel="nofollow">seems to do what i want</a> in respect to 3D math.
it contins a 3D vector class and a 4X4 matrix class capable of transformations like rotate,translate and scale.</p>
<p><a href="http://partiallydisassembled.net/euclid/matrix-classes.html" rel="nofollow">matrix</a> creation is simple, simply pass along the arguments and the matrix is created.</p>
<pre><code>>>> m = Matrix4()
>>> m.translate(50,50,50)
Matrix4([ 1.00 0.00 0.00 50.00
0.00 1.00 0.00 50.00
0.00 0.00 1.00 50.00
0.00 0.00 0.00 1.00])
</code></pre>
<p>the lbrary comes with a 3D vector class, if i wanted to translate a 3D point with this matrix i would need to first create the <a href="http://partiallydisassembled.net/euclid/vector-classes.html" rel="nofollow">vector class</a>, like this.</p>
<pre><code>>>> v = Vector3(100,200,300)
>>> v
Vector3(100.00, 200.00, 300.00)
>>> v.x
100
>>> v.y
200
>>> v.z
300
</code></pre>
<p>Now the Matrix4() class comes with a method to transform coordinates, and its used like so.</p>
<pre><code>>>> m.transform(v)
Point3(150.00, 250.00, 350.00)
</code></pre>
<p>this is great, however, there is no perspective projection applied, the library comes with a method called Matrix4.new_perspective(fov_y, aspect, near, far).
Thats where the problem lies, i have no idea how to use this function properly, (m.transform(vector3) doesent produce anything usable )the <a href="http://partiallydisassembled.net/euclid/matrix-classes.html#SECTION002320000000000000000" rel="nofollow">documentation</a> doesent show how its used with vectors or other matrices, it says something about being 'equivalent to the OpenGL call gluPerspective.fov_y', but ive never used opengl so that wont help.</p>
<p><a href="http://pyeuclid.googlecode.com/svn/trunk/euclid.py" rel="nofollow">this is the module</a> (from euclid import Vector3 , Matrix4)</p>
<p>what i dont want, is recomendtions for some game engine/visulization library, or something thats bent on drawing something to the screen, i just want to know if i can use this library to to turn 3D vector coordnates into 2D screen coordinates, and if not what library can i use???</p>
<p>so get in there and help out noob in distress! :-)
thank you for your help.</p>
| 0 | 2009-10-13T09:14:37Z | 1,559,108 | <p><a href="http://gpwiki.org/index.php/OpenGL%5FTutorial%5FFramework%3AFirst%5FPolygon" rel="nofollow">This tutorial</a> explains the arguments to <a href="http://www.opengl.org/documentation/specs/man%5Fpages/hardcopy/GL/html/glu/perspective.html" rel="nofollow">gluPerspective()</a>, and should transfer over since your library is written with that as a model.</p>
<p>I would expect the new_perspective() method to work like a constructor, i.e. it returns a Matrix set up as a perspective transformation. You should then be able to transform world-space coordinates into perspective-projected coordinates by multiplying vectors with that matrix.</p>
| 0 | 2009-10-13T09:21:06Z | [
"python",
"3d",
"vector",
"matrix",
"projection"
] |
How do i use perspective projection in this library | 1,559,083 | <p>i found a library called <a href="http://code.google.com/p/pyeuclid/" rel="nofollow">pyeuclid</a> and it <a href="http://partiallydisassembled.net/euclid/index.html" rel="nofollow">seems to do what i want</a> in respect to 3D math.
it contins a 3D vector class and a 4X4 matrix class capable of transformations like rotate,translate and scale.</p>
<p><a href="http://partiallydisassembled.net/euclid/matrix-classes.html" rel="nofollow">matrix</a> creation is simple, simply pass along the arguments and the matrix is created.</p>
<pre><code>>>> m = Matrix4()
>>> m.translate(50,50,50)
Matrix4([ 1.00 0.00 0.00 50.00
0.00 1.00 0.00 50.00
0.00 0.00 1.00 50.00
0.00 0.00 0.00 1.00])
</code></pre>
<p>the lbrary comes with a 3D vector class, if i wanted to translate a 3D point with this matrix i would need to first create the <a href="http://partiallydisassembled.net/euclid/vector-classes.html" rel="nofollow">vector class</a>, like this.</p>
<pre><code>>>> v = Vector3(100,200,300)
>>> v
Vector3(100.00, 200.00, 300.00)
>>> v.x
100
>>> v.y
200
>>> v.z
300
</code></pre>
<p>Now the Matrix4() class comes with a method to transform coordinates, and its used like so.</p>
<pre><code>>>> m.transform(v)
Point3(150.00, 250.00, 350.00)
</code></pre>
<p>this is great, however, there is no perspective projection applied, the library comes with a method called Matrix4.new_perspective(fov_y, aspect, near, far).
Thats where the problem lies, i have no idea how to use this function properly, (m.transform(vector3) doesent produce anything usable )the <a href="http://partiallydisassembled.net/euclid/matrix-classes.html#SECTION002320000000000000000" rel="nofollow">documentation</a> doesent show how its used with vectors or other matrices, it says something about being 'equivalent to the OpenGL call gluPerspective.fov_y', but ive never used opengl so that wont help.</p>
<p><a href="http://pyeuclid.googlecode.com/svn/trunk/euclid.py" rel="nofollow">this is the module</a> (from euclid import Vector3 , Matrix4)</p>
<p>what i dont want, is recomendtions for some game engine/visulization library, or something thats bent on drawing something to the screen, i just want to know if i can use this library to to turn 3D vector coordnates into 2D screen coordinates, and if not what library can i use???</p>
<p>so get in there and help out noob in distress! :-)
thank you for your help.</p>
| 0 | 2009-10-13T09:14:37Z | 1,582,064 | <p>I don't know if this is relevant as you may already know this but you'll need a view matrix too. The view matrix represents the inverse of the transform of your camera in the world. You may find the matrix class also has helper methods for creating view matrices, sometimes called lookAt os similar. Alternatively just create a matrix manually that positions and orientates your (imaginary) camera and then invert it.</p>
<p>If you apply the projection matrix to world co-ords you're making the implicit assumption that your view matrix is the identity and so your camera is at the origin of the world and pointing down an axis. Which axis that is will depend on the projection matrix but if it's like most other systems it'll be the z-axis since convention has camera depth measured along z. It could be in either the positive or negative direction so again check the documentation for details.</p>
<p>So, to summarise, you need to multiply your model matrix with the view matrix and <em>then</em> by the projection matrix. The projection matrix is designed to work in camera coordinates rather than world coordinates.</p>
| 0 | 2009-10-17T12:06:05Z | [
"python",
"3d",
"vector",
"matrix",
"projection"
] |
String arguments in python multiprocessing | 1,559,125 | <p>I'm trying to pass a string argument to a target function in a process. Somehow, the string is interpreted as a list of as many arguments as there are characters.</p>
<p>This is the code:</p>
<pre><code>import multiprocessing
def write(s):
print s
write('hello')
p = multiprocessing.Process(target=write, args=('hello'))
p.start()
</code></pre>
<p>I get this output:</p>
<pre><code>hello
Process Process-1:
Traceback (most recent call last):
>>> File "/usr/local/lib/python2.5/site-packages/multiprocessing/process.py", line 237, in _bootstrap
self.run()
File "/usr/local/lib/python2.5/site-packages/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
TypeError: write() takes exactly 1 argument (5 given)
>>>
</code></pre>
<p>What am I doing wrong? How am I supposed to pass a stringn?</p>
<p>Thanks, Ariel</p>
| 14 | 2009-10-13T09:27:27Z | 1,559,143 | <p>You have to pass</p>
<pre><code>p = multiprocessing.Process(target=write, args=('hello',))
</code></pre>
<p>Notice the comma! Otherwise it is interpreted as a simple string and not as a 1 element tuple.</p>
| 1 | 2009-10-13T09:32:23Z | [
"python",
"string",
"multiprocessing",
"arguments"
] |
String arguments in python multiprocessing | 1,559,125 | <p>I'm trying to pass a string argument to a target function in a process. Somehow, the string is interpreted as a list of as many arguments as there are characters.</p>
<p>This is the code:</p>
<pre><code>import multiprocessing
def write(s):
print s
write('hello')
p = multiprocessing.Process(target=write, args=('hello'))
p.start()
</code></pre>
<p>I get this output:</p>
<pre><code>hello
Process Process-1:
Traceback (most recent call last):
>>> File "/usr/local/lib/python2.5/site-packages/multiprocessing/process.py", line 237, in _bootstrap
self.run()
File "/usr/local/lib/python2.5/site-packages/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
TypeError: write() takes exactly 1 argument (5 given)
>>>
</code></pre>
<p>What am I doing wrong? How am I supposed to pass a stringn?</p>
<p>Thanks, Ariel</p>
| 14 | 2009-10-13T09:27:27Z | 1,559,147 | <p>Change <code>args=('hello')</code> to <code>args=('hello',)</code> or even better <code>args=['hello']</code>. Otherwise parentheses don't form a sequence.</p>
| 5 | 2009-10-13T09:32:46Z | [
"python",
"string",
"multiprocessing",
"arguments"
] |
String arguments in python multiprocessing | 1,559,125 | <p>I'm trying to pass a string argument to a target function in a process. Somehow, the string is interpreted as a list of as many arguments as there are characters.</p>
<p>This is the code:</p>
<pre><code>import multiprocessing
def write(s):
print s
write('hello')
p = multiprocessing.Process(target=write, args=('hello'))
p.start()
</code></pre>
<p>I get this output:</p>
<pre><code>hello
Process Process-1:
Traceback (most recent call last):
>>> File "/usr/local/lib/python2.5/site-packages/multiprocessing/process.py", line 237, in _bootstrap
self.run()
File "/usr/local/lib/python2.5/site-packages/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
TypeError: write() takes exactly 1 argument (5 given)
>>>
</code></pre>
<p>What am I doing wrong? How am I supposed to pass a stringn?</p>
<p>Thanks, Ariel</p>
| 14 | 2009-10-13T09:27:27Z | 1,559,149 | <p>This is a common gotcha in Python - if you want to have a tuple with only one element, you need to specify that it's actually a tuple (and not just something with brackets around it) - this is done by adding a comma after the element.</p>
<p>To fix this, just put a comma after the string, inside the brackets:</p>
<pre><code>p = multiprocessing.Process(target=write, args=('hello',))
</code></pre>
<p>That way, Python will recognise it as a tuple with a single element, as intended. Currently, Python is interpreting your code as just a string. However, it's failing in this particular way because a string is effectively list of characters. So Python is thinking that you want to pass ('h', 'e', 'l', 'l', 'o'). That's why it's saying "you gave me 5 parameters".</p>
| 37 | 2009-10-13T09:33:44Z | [
"python",
"string",
"multiprocessing",
"arguments"
] |
Which is the most pythonic: installing python modules via a package manager ( macports, apt) or via pip/easy_install/setuptools | 1,559,372 | <p>Usually I tend to install things via the package manager, for unixy stuff. However, when I programmed a lot of perl, I would use CPAN, newer versions and all that.</p>
<p>In general, I used to install system stuff via package manager, and language stuff via it's own package manager ( gem/easy_install|pip/cpan)</p>
<p>Now using python primarily, I am wondering what best practice is?</p>
| 11 | 2009-10-13T10:25:31Z | 1,559,436 | <p>The system python version and its libraries are often used by software in the distribution. As long as the software you are using are happy with the same versions of python and all the libraries as your distribution is, than using the distribution packages will work just fine.</p>
<p>However, quite often you need development version of packages, or newer version, or older versions. And then it doesn't work any more.</p>
<p>It is therefore usually recommeded to install your own Python version that you use for development, and create development environments with <a href="http://pypi.python.org/pypi/zc.buildout">buildout</a> or <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a> or both, to isolate the system python and the development environment from each other.</p>
| 17 | 2009-10-13T10:41:50Z | [
"python",
"setuptools",
"distutils",
"pip"
] |
Which is the most pythonic: installing python modules via a package manager ( macports, apt) or via pip/easy_install/setuptools | 1,559,372 | <p>Usually I tend to install things via the package manager, for unixy stuff. However, when I programmed a lot of perl, I would use CPAN, newer versions and all that.</p>
<p>In general, I used to install system stuff via package manager, and language stuff via it's own package manager ( gem/easy_install|pip/cpan)</p>
<p>Now using python primarily, I am wondering what best practice is?</p>
| 11 | 2009-10-13T10:25:31Z | 1,559,521 | <p>There are two completely opposing camps: one in favor of system-provided packages, and one in favor of separate installation. I'm personally in the "system packages" camp. I'll provide arguments from each side below.</p>
<p>Pro system packages: system packager already cares about dependency, and compliance with overall system policies (such as file layout). System packages provide security updates while still caring about not breaking compatibility - so they sometimes backport security fixes that the upstream authors did not backport. System packages are "safe" wrt. system upgrades: after a system upgrade, you probably also have a new Python version, but all your Python modules are still there if they come from a system packager. That's all personal experience with Debian.</p>
<p>Con system packages: not all software may be provided as a system package, or not in the latest version; installing stuff yourself into the system may break system packages. Upgrades may break your application.</p>
<p>Pro separate installation: Some people (in particular web application developers) argue that you absolutely need a repeatable setup, with just the packages you want, and completely decoupled from system Python. This goes beyond self-installed vs. system packages, since even for self-installed, you might still modify the system python; with the separate installation, you won't. As Lennart discusses, there are now dedicated tool chains to support this setup. People argue that only this approach can guarantee repeatable results.</p>
<p>Con separate installation: you need to deal with bug fixes yourself, and you need to make sure all your users use the separate installation. In the case of web applications, the latter is typically easy to achieve.</p>
| 17 | 2009-10-13T10:57:17Z | [
"python",
"setuptools",
"distutils",
"pip"
] |
Regular Expression for HTML artifacts | 1,559,375 | <p>I some text with HTML artifacts where the <code><</code> and <code>></code> of tags got dropped, so now I need something that will match a small <code>p</code> followed by a capital letter, like</p>
<pre><code>pThe next day they....
</code></pre>
<p>And I also need something that will catch the trailing <code>/p</code> which is easier. These need to be stripped, i.e. replaced with <code>""</code> in python.</p>
<p>What RE would I use for that? Thanks!
Stephan.</p>
| 0 | 2009-10-13T10:26:13Z | 1,559,411 | <p>Try this:</p>
<pre><code>re.sub(r"(/?p)(?=[A-Z]|$)", r"<\1>", str)
</code></pre>
<p>You might want to extend the boundary assertion (here <code>(?=[A-Z]|$)</code>) with additional characters like whitespace.</p>
| 1 | 2009-10-13T10:35:09Z | [
"python",
"html",
"regex"
] |
Regular Expression for HTML artifacts | 1,559,375 | <p>I some text with HTML artifacts where the <code><</code> and <code>></code> of tags got dropped, so now I need something that will match a small <code>p</code> followed by a capital letter, like</p>
<pre><code>pThe next day they....
</code></pre>
<p>And I also need something that will catch the trailing <code>/p</code> which is easier. These need to be stripped, i.e. replaced with <code>""</code> in python.</p>
<p>What RE would I use for that? Thanks!
Stephan.</p>
| 0 | 2009-10-13T10:26:13Z | 1,559,426 | <p>I got is. You use backreferences,</p>
<pre><code>import re
smallBig = re.compile(r'[a-z]([A-Z])')
...
cleanedString = smallBig.sub(r'\1', dirtyString)
</code></pre>
<p>This removes the small letter but keeps the capital letter in cases where the '<' and '>' of html tags were stripped and you sit with text like </p>
<p>pSome new paragraph text /p</p>
<p>Quick and dirty but it works in my case.</p>
| 1 | 2009-10-13T10:38:16Z | [
"python",
"html",
"regex"
] |
coverage.py: exclude files | 1,559,424 | <p>How do I exclude entire files from <a href="http://nedbatchelder.com/code/coverage/">coverage.py</a> reports?</p>
<p>According to the documentation you can exclude code by matching lines. I want to exclude entire files, so that the reports don't include 3rd party libraries. Am I missing something? Can it be done?</p>
| 24 | 2009-10-13T10:38:04Z | 1,559,639 | <p>You can omit modules with the --omit flag. It takes a comma-separated list of path prefixes. So for example:</p>
<pre><code>coverage run my_program.py
coverage report --omit=path/to/3rdparty
</code></pre>
| 34 | 2009-10-13T11:28:08Z | [
"python",
"testing",
"software-quality",
"code-coverage",
"coverage.py"
] |
coverage.py: exclude files | 1,559,424 | <p>How do I exclude entire files from <a href="http://nedbatchelder.com/code/coverage/">coverage.py</a> reports?</p>
<p>According to the documentation you can exclude code by matching lines. I want to exclude entire files, so that the reports don't include 3rd party libraries. Am I missing something? Can it be done?</p>
| 24 | 2009-10-13T10:38:04Z | 19,678,723 | <p>Omitting some files worked for me using coverage API.
Well it is the same kind what Ned suggested.</p>
<p>Here it is how I did it:</p>
<p><code>cov = coverage.coverage(omit='/usr/lib/python2.6/site-packages/*')</code></p>
| 9 | 2013-10-30T09:42:18Z | [
"python",
"testing",
"software-quality",
"code-coverage",
"coverage.py"
] |
How to send a dictionary to a function that accepts **kwargs? | 1,559,638 | <p>I have a function that accepts wildcard keyword parameters:</p>
<pre><code>def func(**kargs):
doA
doB
</code></pre>
<p>How do I send it a dictionary?</p>
| 18 | 2009-10-13T11:28:05Z | 1,559,646 | <p><code>func(**mydict)</code></p>
<p>this will mean kwargs=mydict inside the function</p>
<p>all the keys of mydict must be strings</p>
| 4 | 2009-10-13T11:30:24Z | [
"python"
] |
How to send a dictionary to a function that accepts **kwargs? | 1,559,638 | <p>I have a function that accepts wildcard keyword parameters:</p>
<pre><code>def func(**kargs):
doA
doB
</code></pre>
<p>How do I send it a dictionary?</p>
| 18 | 2009-10-13T11:28:05Z | 1,559,652 | <p>Just use <code>func(**some_dict)</code> to call it.</p>
<p>This is documented on <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists">section 4.7.4 of python tutorial</a>.</p>
<p>Note that the <em>same</em> <code>dict</code> is <strong>not</strong> passed into the function. A new copy is created, so <code>some_dict is not kwargs</code>.</p>
| 35 | 2009-10-13T11:31:36Z | [
"python"
] |
How to send a dictionary to a function that accepts **kwargs? | 1,559,638 | <p>I have a function that accepts wildcard keyword parameters:</p>
<pre><code>def func(**kargs):
doA
doB
</code></pre>
<p>How do I send it a dictionary?</p>
| 18 | 2009-10-13T11:28:05Z | 1,559,861 | <p>It's not 100% clear by your question, but if you'd like to pass a <code>dict</code> in through <code>kwargs</code>, you just make that dict a part of another dict, like so:</p>
<pre><code>my_dict = {} #the dict you want to pass to func
kwargs = {'my_dict': my_dict } #the keyword argument container
func(**kwargs) #calling the function
</code></pre>
<p>Then you can catch <code>my_dict</code> in the function:</p>
<pre><code>def func(**kwargs):
my_dict = kwargs.get('my_dict')
</code></pre>
<p>or...</p>
<pre><code>def func(my_dict, **kwargs):
#reference my_dict directly from here
my_dict['new_key'] = 1234
</code></pre>
<p>I use the latter a lot when I have the same set of options passed to different functions, but some functions only use some the options (I hope that makes sense...).
But there are of course a million ways to go about this. If you elaborate a bit on your problem we could most likely help you better.</p>
| 4 | 2009-10-13T12:18:54Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.