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
Allowing user to configure cron
1,136,168
<p>I have this bash script on the server that runs every hour, via cron. I was perfectly happy, but now the user wants to be able to configure the frequency through the web interface.</p> <p>I don't feel comfortable manipulating the cron configuration programmatically, but I'm not sure if the other options are any better.</p> <p>The way I see it, I can either:</p> <ul> <li>Schedule a script to run once a minute and check if it should really run "now"</li> <li>Forgo cron altogether and use a deamon that is its own scheduler. This probably means rewriting the script in python</li> <li>...or suck it up and manipulate the cron configuration from the web interface (written in python BTW)</li> </ul> <p>What should I do?</p> <p>EDIT: to clarify, the main reason I'm apprehensive about manipulating cron is because it's basically text manipulation with no validation, and if I mess it up, none of my other cron jobs will run.</p> <p><strong>Here's what I ended up doing:</strong></p> <p>Taking stefanw's advice, I added the following line at the top of my bash script:</p> <pre><code>if [ ! `cat /home/username/settings/run.freq` = $1 ]; then exit 0 fi </code></pre> <p>I set up the following cron jobs:</p> <pre><code>0 */2 * * * /home/username/scripts/publish.sh 2_hours @hourly /home/username/scripts/publish.sh 1_hour */30 * * * * /home/username/scripts/publish.sh 30_minutes */10 * * * * /home/username/scripts/publish.sh 10_minutes </code></pre> <p>From the web interface, I let the user choose between those four options, and based on what the user chose, I write the string <code>2_hours/1_hour/30_minutes/10_minutes</code> into the file at <code>/home/username/settings/run.freq</code>.</p> <p>I don't love it, but it seems like the best alternative.</p>
3
2009-07-16T08:25:31Z
1,136,245
<p>What about <a href="http://webmin.com" rel="nofollow" title="Webmin">Webmin</a>? I have never used it myself but it seems you could configure the cron module and give permissions to the user who wants to configure the job.</p>
0
2009-07-16T08:43:30Z
[ "python", "bash", "cron" ]
Allowing user to configure cron
1,136,168
<p>I have this bash script on the server that runs every hour, via cron. I was perfectly happy, but now the user wants to be able to configure the frequency through the web interface.</p> <p>I don't feel comfortable manipulating the cron configuration programmatically, but I'm not sure if the other options are any better.</p> <p>The way I see it, I can either:</p> <ul> <li>Schedule a script to run once a minute and check if it should really run "now"</li> <li>Forgo cron altogether and use a deamon that is its own scheduler. This probably means rewriting the script in python</li> <li>...or suck it up and manipulate the cron configuration from the web interface (written in python BTW)</li> </ul> <p>What should I do?</p> <p>EDIT: to clarify, the main reason I'm apprehensive about manipulating cron is because it's basically text manipulation with no validation, and if I mess it up, none of my other cron jobs will run.</p> <p><strong>Here's what I ended up doing:</strong></p> <p>Taking stefanw's advice, I added the following line at the top of my bash script:</p> <pre><code>if [ ! `cat /home/username/settings/run.freq` = $1 ]; then exit 0 fi </code></pre> <p>I set up the following cron jobs:</p> <pre><code>0 */2 * * * /home/username/scripts/publish.sh 2_hours @hourly /home/username/scripts/publish.sh 1_hour */30 * * * * /home/username/scripts/publish.sh 30_minutes */10 * * * * /home/username/scripts/publish.sh 10_minutes </code></pre> <p>From the web interface, I let the user choose between those four options, and based on what the user chose, I write the string <code>2_hours/1_hour/30_minutes/10_minutes</code> into the file at <code>/home/username/settings/run.freq</code>.</p> <p>I don't love it, but it seems like the best alternative.</p>
3
2009-07-16T08:25:31Z
1,136,329
<p>You could use a python scheduler library that does most of the work already:</p> <ul> <li><a href="http://www.kalab.com/freeware/pycron/pycron.htm" rel="nofollow">pycron</a></li> <li><a href="http://code.google.com/p/scheduler-py/" rel="nofollow">scheduler-py</a></li> </ul>
3
2009-07-16T09:04:18Z
[ "python", "bash", "cron" ]
Allowing user to configure cron
1,136,168
<p>I have this bash script on the server that runs every hour, via cron. I was perfectly happy, but now the user wants to be able to configure the frequency through the web interface.</p> <p>I don't feel comfortable manipulating the cron configuration programmatically, but I'm not sure if the other options are any better.</p> <p>The way I see it, I can either:</p> <ul> <li>Schedule a script to run once a minute and check if it should really run "now"</li> <li>Forgo cron altogether and use a deamon that is its own scheduler. This probably means rewriting the script in python</li> <li>...or suck it up and manipulate the cron configuration from the web interface (written in python BTW)</li> </ul> <p>What should I do?</p> <p>EDIT: to clarify, the main reason I'm apprehensive about manipulating cron is because it's basically text manipulation with no validation, and if I mess it up, none of my other cron jobs will run.</p> <p><strong>Here's what I ended up doing:</strong></p> <p>Taking stefanw's advice, I added the following line at the top of my bash script:</p> <pre><code>if [ ! `cat /home/username/settings/run.freq` = $1 ]; then exit 0 fi </code></pre> <p>I set up the following cron jobs:</p> <pre><code>0 */2 * * * /home/username/scripts/publish.sh 2_hours @hourly /home/username/scripts/publish.sh 1_hour */30 * * * * /home/username/scripts/publish.sh 30_minutes */10 * * * * /home/username/scripts/publish.sh 10_minutes </code></pre> <p>From the web interface, I let the user choose between those four options, and based on what the user chose, I write the string <code>2_hours/1_hour/30_minutes/10_minutes</code> into the file at <code>/home/username/settings/run.freq</code>.</p> <p>I don't love it, but it seems like the best alternative.</p>
3
2009-07-16T08:25:31Z
1,138,065
<p>Well something I use is a main script started every minute by cron. this script check touched files. If the files are there the main cron script start a function/subscript. You just have to touch a defined file and "rm -f"ed it when done. It has the side benefits to be more concurrent proof if you want other way to start jobs. Then you can use your favourite web programming language to handle your users scheduling ...</p> <p>The main script looks like :</p> <pre><code>[...] if [ -e "${tag_archive_log_files}" ]; then archive_log_files ${params} rm -f ${tag_archive_files} fi if [ -e "${tag_purge_log_files}" ]; then purge_log_files ${params} rm -f ${tag_purge_log_files} fi [...] </code></pre>
0
2009-07-16T14:36:54Z
[ "python", "bash", "cron" ]
Allowing user to configure cron
1,136,168
<p>I have this bash script on the server that runs every hour, via cron. I was perfectly happy, but now the user wants to be able to configure the frequency through the web interface.</p> <p>I don't feel comfortable manipulating the cron configuration programmatically, but I'm not sure if the other options are any better.</p> <p>The way I see it, I can either:</p> <ul> <li>Schedule a script to run once a minute and check if it should really run "now"</li> <li>Forgo cron altogether and use a deamon that is its own scheduler. This probably means rewriting the script in python</li> <li>...or suck it up and manipulate the cron configuration from the web interface (written in python BTW)</li> </ul> <p>What should I do?</p> <p>EDIT: to clarify, the main reason I'm apprehensive about manipulating cron is because it's basically text manipulation with no validation, and if I mess it up, none of my other cron jobs will run.</p> <p><strong>Here's what I ended up doing:</strong></p> <p>Taking stefanw's advice, I added the following line at the top of my bash script:</p> <pre><code>if [ ! `cat /home/username/settings/run.freq` = $1 ]; then exit 0 fi </code></pre> <p>I set up the following cron jobs:</p> <pre><code>0 */2 * * * /home/username/scripts/publish.sh 2_hours @hourly /home/username/scripts/publish.sh 1_hour */30 * * * * /home/username/scripts/publish.sh 30_minutes */10 * * * * /home/username/scripts/publish.sh 10_minutes </code></pre> <p>From the web interface, I let the user choose between those four options, and based on what the user chose, I write the string <code>2_hours/1_hour/30_minutes/10_minutes</code> into the file at <code>/home/username/settings/run.freq</code>.</p> <p>I don't love it, but it seems like the best alternative.</p>
3
2009-07-16T08:25:31Z
1,151,998
<p>I found a module that can manipulate the cron info for me. It's called <a href="http://pypi.python.org/pypi/python-crontab/0.9" rel="nofollow">python-crontab</a>, and it's available with <code>easy_install</code>. From the <a href="http://bazaar.launchpad.net/~doctormo/python-crontab/trunk/annotate/head:/crontab.py" rel="nofollow">source</a>:</p> <pre><code>Example Use: from crontab import CronTab tab = CronTab() cron = tab.new(command='/usr/bin/echo') cron.minute().during(5,50).every(5) cron.hour().every(4) cron2 = tab.new(command='/foo/bar',comment='SomeID') cron2.every_reboot() list = tab.find('bar') cron3 = list[0] cron3.clear() cron3.minute().every(1) print unicode(tab.render()) for cron4 in tab.find('echo'): print cron4 for cron5 in tab: print cron5 tab.remove_all('echo') t.write() </code></pre> <p>(I kept googling for "cron" and couldn't find anything. The keyword I was missing was "crontab").</p> <p>I'm now deciding if I'll use this or just replace cron entirely with a python based scheduler.</p>
0
2009-07-20T06:44:40Z
[ "python", "bash", "cron" ]
Inserting a Python datetime.datetime object into MySQL
1,136,437
<p>I have a date column in a MySQL table. I want to insert a <code>datetime.datetime()</code> object into this column. What should I be using in the execute statement?</p> <p>I have tried:</p> <pre><code>now = datetime.datetime(2009,5,5) cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s , %s)",("name", 4,now)) </code></pre> <p>I am getting an error as: <code>"TypeError: not all arguments converted during string formatting"</code> What should I use instead of <code>%s</code>?</p>
72
2009-07-16T09:29:48Z
1,136,480
<p>Try using <code>now.date()</code> to get a <code>Date</code> object rather than a <code>DateTime</code>.</p> <p>If that doesn't work, then converting that to a string should work:</p> <pre><code>now = datetime.datetime(2009,5,5) str_now = now.date().isoformat() cursor.execute('INSERT INTO table (name, id, datecolumn) VALUES (%s,%s,%s)', ('name',4,str_now)) </code></pre>
5
2009-07-16T09:39:15Z
[ "python", "mysql", "datetime" ]
Inserting a Python datetime.datetime object into MySQL
1,136,437
<p>I have a date column in a MySQL table. I want to insert a <code>datetime.datetime()</code> object into this column. What should I be using in the execute statement?</p> <p>I have tried:</p> <pre><code>now = datetime.datetime(2009,5,5) cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s , %s)",("name", 4,now)) </code></pre> <p>I am getting an error as: <code>"TypeError: not all arguments converted during string formatting"</code> What should I use instead of <code>%s</code>?</p>
72
2009-07-16T09:29:48Z
1,138,297
<p>What database are you connecting to? I know Oracle can be picky about date formats and likes <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="nofollow">ISO&nbsp;8601</a> format.</p> <p>**Note: Oops, I just read you are on MySQL. Just format the date and try it as a separate direct SQL call to test.</p> <p>In Python, you can get an ISO date like</p> <pre><code>now.isoformat() </code></pre> <p>For instance, Oracle likes dates like</p> <pre><code>insert into x values(99, '31-may-09'); </code></pre> <p>Depending on your database, if it is Oracle you might need to TO_DATE it:</p> <pre><code>insert into x values(99, to_date('2009/05/31:12:00:00AM', 'yyyy/mm/dd:hh:mi:ssam')); </code></pre> <p>The general usage of TO_DATE is:</p> <pre><code>TO_DATE(&lt;string&gt;, '&lt;format&gt;') </code></pre> <p>If using another database (I saw the cursor and thought Oracle; I could be wrong) then check their date format tools. For MySQL it is DATE_FORMAT() and SQL&nbsp;Server it is CONVERT.</p> <p>Also using a tool like <a href="https://en.wikipedia.org/wiki/SQLAlchemy" rel="nofollow">SQLAlchemy</a> will remove differences like these and make your life easy.</p>
1
2009-07-16T15:08:32Z
[ "python", "mysql", "datetime" ]
Inserting a Python datetime.datetime object into MySQL
1,136,437
<p>I have a date column in a MySQL table. I want to insert a <code>datetime.datetime()</code> object into this column. What should I be using in the execute statement?</p> <p>I have tried:</p> <pre><code>now = datetime.datetime(2009,5,5) cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s , %s)",("name", 4,now)) </code></pre> <p>I am getting an error as: <code>"TypeError: not all arguments converted during string formatting"</code> What should I use instead of <code>%s</code>?</p>
72
2009-07-16T09:29:48Z
4,508,923
<p>For a time field, use:</p> <pre><code>import time time.strftime('%Y-%m-%d %H:%M:%S') </code></pre> <p>I think strftime also applies to datetime.</p>
105
2010-12-22T11:56:18Z
[ "python", "mysql", "datetime" ]
Inserting a Python datetime.datetime object into MySQL
1,136,437
<p>I have a date column in a MySQL table. I want to insert a <code>datetime.datetime()</code> object into this column. What should I be using in the execute statement?</p> <p>I have tried:</p> <pre><code>now = datetime.datetime(2009,5,5) cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s , %s)",("name", 4,now)) </code></pre> <p>I am getting an error as: <code>"TypeError: not all arguments converted during string formatting"</code> What should I use instead of <code>%s</code>?</p>
72
2009-07-16T09:29:48Z
12,191,497
<p>You are most likely getting the TypeError because you need quotes around the datecolumn value.</p> <p>Try:</p> <pre><code>now = datetime.datetime(2009, 5, 5) cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, '%s')", ("name", 4, now)) </code></pre> <p>With regards to the format, I had success with the above command (which includes the milliseconds) and with:</p> <pre><code>now.strftime('%Y-%m-%d %H:%M:%S') </code></pre> <p>Hope this helps.</p>
28
2012-08-30T06:59:51Z
[ "python", "mysql", "datetime" ]
how do I use the json google translate api?
1,136,604
<p>I am trying to use google translate from python with utf-8 text. How do I call the json api? They have a document for embedding it in html but I can't find a proper API or wsdl anywhere.</p> <p>Thanks Raphael</p>
3
2009-07-16T10:03:38Z
1,136,915
<p>I think you are talking about the ajax api <a href="http://code.google.com/apis/ajaxlanguage/" rel="nofollow">http://code.google.com/apis/ajaxlanguage/</a>, which has to be used from javascript, so I do not understand what do you mean by "google translate from python"</p> <p>Alternatively if you need to use translate functionality from python, you can directly query the translate page and parse it using xml/html libs e.g. beautiful soup, html5lib</p> <p>Actually I did that once and beautiful soup did not work on google translate but html5lib(<a href="http://code.google.com/p/html5lib/" rel="nofollow">http://code.google.com/p/html5lib/</a>) did</p> <p>you will need to do something like this (copied from my larger code base)</p> <pre><code>def translate(text, tlan, slan="en"): opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'translate.py/0.1')] htmlPage = opener.open( "http://translate.google.com/translate_t?" + urllib.urlencode({'sl': slan, 'tl':tlan}), data=urllib.urlencode({'hl': 'en', 'ie': 'UTF8', 'text': text.encode('utf-8'), 'sl': slan, 'tl': tlan}) ) parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("etree", cElementTree)) etree_document = parser.parse(htmlPage) return _getResult(etree_document) </code></pre>
0
2009-07-16T11:16:35Z
[ "python", "json", "api", "google-translate" ]
how do I use the json google translate api?
1,136,604
<p>I am trying to use google translate from python with utf-8 text. How do I call the json api? They have a document for embedding it in html but I can't find a proper API or wsdl anywhere.</p> <p>Thanks Raphael</p>
3
2009-07-16T10:03:38Z
1,137,820
<p>Here is the code that finally works for me. Using the website without the ajax api can get your ip banned, so this is better.</p> <pre><code>#!/usr/bin/env python from urllib2 import urlopen from urllib import urlencode import urllib2 import urllib import simplejson import sys # The google translate API can be found here: # http://code.google.com/apis/ajaxlanguage/documentation/#Examples def translate(text = 'hola querida'): tl="es" sl="en" langpair='%s|%s'%(tl,sl) base_url='http://ajax.googleapis.com/ajax/services/language/translate?' data = urllib.urlencode({'v':1.0,'ie': 'UTF8', 'q': text.encode('utf-8'), 'langpair':langpair}) url = base_url+data search_results = urllib.urlopen(url) json = simplejson.loads(search_results.read()) result = json['responseData']['translatedText'] return result </code></pre>
7
2009-07-16T14:02:54Z
[ "python", "json", "api", "google-translate" ]
how do I use the json google translate api?
1,136,604
<p>I am trying to use google translate from python with utf-8 text. How do I call the json api? They have a document for embedding it in html but I can't find a proper API or wsdl anywhere.</p> <p>Thanks Raphael</p>
3
2009-07-16T10:03:38Z
2,518,499
<p>Look what I have found : <a href="http://code.google.com/intl/ru/apis/ajaxlanguage/terms.html" rel="nofollow">http://code.google.com/intl/ru/apis/ajaxlanguage/terms.html</a></p> <p>Here is the interesting part:</p> <p>You will not, and will not permit your end users or other third parties to: .... * submit any request exceeding 5000 characters in length; ....</p>
1
2010-03-25T18:57:42Z
[ "python", "json", "api", "google-translate" ]
how do I use the json google translate api?
1,136,604
<p>I am trying to use google translate from python with utf-8 text. How do I call the json api? They have a document for embedding it in html but I can't find a proper API or wsdl anywhere.</p> <p>Thanks Raphael</p>
3
2009-07-16T10:03:38Z
5,846,907
<p>Use xgoogle from Peteris Kramins (<a href="http://www.catonmat.net/blog/python-library-for-google-translate/" rel="nofollow">His blog</a>)</p> <pre><code>&gt;&gt;&gt; from xgoogle.translate import Translator &gt;&gt;&gt; &gt;&gt;&gt; translate = Translator().translate &gt;&gt;&gt; &gt;&gt;&gt; print translate("Mani sauc Pēteris", lang_to="en") My name is Peter &gt;&gt;&gt; &gt;&gt;&gt; print translate("Mani sauc Pēteris", lang_to="ru").encode('utf-8') Меня зовут Петр &gt;&gt;&gt; &gt;&gt;&gt; print translate("Меня зовут Петр") My name is Peter </code></pre>
2
2011-05-01T06:37:20Z
[ "python", "json", "api", "google-translate" ]
When should I use varargs in designing a Python API?
1,136,673
<p>Is there a good rule of thumb as to when you should prefer varargs function signatures in your API over passing an iterable to a function? ("varargs" being short for "variadic" or "variable-number-of-arguments"; i.e. <code>*args</code>)</p> <p>For example, <code>os.path.join</code> has a vararg signature:</p> <pre><code>os.path.join(first_component, *rest) -&gt; str </code></pre> <p>Whereas <code>min</code> allows either:</p> <pre><code>min(iterable[, key=func]) -&gt; val min(a, b, c, ...[, key=func]) -&gt; val </code></pre> <p>Whereas <code>any</code>/<code>all</code> only permit an iterable:</p> <pre><code>any(iterable) -&gt; bool </code></pre>
4
2009-07-16T10:20:20Z
1,136,754
<p>My rule of thumb is to use it when you might often switch between passing one and multiple parameters. Instead of having two functions (some GUI code for example):</p> <pre><code>def enable_tab(tab_name) def enable_tabs(tabs_list) </code></pre> <p>or even worse, having just one function</p> <pre><code>def enable_tabs(tabs_list) </code></pre> <p>and using it as <code>enable_tabls(['tab1'])</code>, I tend to use just: <code>def enable_tabs(*tabs)</code>. Although, seeing something like <code>enable_tabs('tab1')</code> looks kind of wrong (because of the plural), I prefer it over the alternatives.</p>
3
2009-07-16T10:37:13Z
[ "python", "api", "varargs" ]
When should I use varargs in designing a Python API?
1,136,673
<p>Is there a good rule of thumb as to when you should prefer varargs function signatures in your API over passing an iterable to a function? ("varargs" being short for "variadic" or "variable-number-of-arguments"; i.e. <code>*args</code>)</p> <p>For example, <code>os.path.join</code> has a vararg signature:</p> <pre><code>os.path.join(first_component, *rest) -&gt; str </code></pre> <p>Whereas <code>min</code> allows either:</p> <pre><code>min(iterable[, key=func]) -&gt; val min(a, b, c, ...[, key=func]) -&gt; val </code></pre> <p>Whereas <code>any</code>/<code>all</code> only permit an iterable:</p> <pre><code>any(iterable) -&gt; bool </code></pre>
4
2009-07-16T10:20:20Z
1,136,791
<p>You should use it when your parameter list is variable.</p> <p>Yeah, I know the answer is kinda daft, but it's true. Maybe your question was a bit diffuse. :-)</p> <p>Default arguments, like min() above is more useful when you either want to different behaviours (like min() above) or when you simply don't want to force the caller to send in all parameters.</p> <p>The *arg is for when you have a variable list of arguments of the same type. Joining is a typical example. You can replace it with an argument that takes a list as well.</p> <p>**kw is for when you have many arguments of different types, where each argument also is connected to a name. A typical example is when you want a generic function for handling form submission or similar.</p>
0
2009-07-16T10:46:28Z
[ "python", "api", "varargs" ]
When should I use varargs in designing a Python API?
1,136,673
<p>Is there a good rule of thumb as to when you should prefer varargs function signatures in your API over passing an iterable to a function? ("varargs" being short for "variadic" or "variable-number-of-arguments"; i.e. <code>*args</code>)</p> <p>For example, <code>os.path.join</code> has a vararg signature:</p> <pre><code>os.path.join(first_component, *rest) -&gt; str </code></pre> <p>Whereas <code>min</code> allows either:</p> <pre><code>min(iterable[, key=func]) -&gt; val min(a, b, c, ...[, key=func]) -&gt; val </code></pre> <p>Whereas <code>any</code>/<code>all</code> only permit an iterable:</p> <pre><code>any(iterable) -&gt; bool </code></pre>
4
2009-07-16T10:20:20Z
1,136,798
<p>Consider using varargs when you expect your users to specify the list of arguments as code at the callsite or having a single value is the common case. When you expect your users to get the arguments from somewhere else, don't use varargs. When in doubt, err on the side of not using varargs.</p> <p>Using your examples, the most common usecase for <em>os.path.join</em> is to have a path prefix and append a filename/relative path onto it, so the call usually looks like <em>os.path.join(prefix, some_file)</em>. On the other hand, <em>any()</em> is usually used to process a list of data, when you know all the elements you don't use <em>any([a,b,c])</em>, you use <em>a or b or c</em>.</p>
8
2009-07-16T10:48:23Z
[ "python", "api", "varargs" ]
When should I use varargs in designing a Python API?
1,136,673
<p>Is there a good rule of thumb as to when you should prefer varargs function signatures in your API over passing an iterable to a function? ("varargs" being short for "variadic" or "variable-number-of-arguments"; i.e. <code>*args</code>)</p> <p>For example, <code>os.path.join</code> has a vararg signature:</p> <pre><code>os.path.join(first_component, *rest) -&gt; str </code></pre> <p>Whereas <code>min</code> allows either:</p> <pre><code>min(iterable[, key=func]) -&gt; val min(a, b, c, ...[, key=func]) -&gt; val </code></pre> <p>Whereas <code>any</code>/<code>all</code> only permit an iterable:</p> <pre><code>any(iterable) -&gt; bool </code></pre>
4
2009-07-16T10:20:20Z
1,136,801
<p>They are completely different interfaces.<br /> In one case, you have one parameter, in the other you have many.</p> <pre><code>any(1, 2, 3) TypeError: any() takes exactly one argument (3 given) os.path.join("1", "2", "3") '1\\2\\3' </code></pre> <p>It really depends on <em>what</em> you want to emphasize: <code>any</code> works over a list (well, sort of), while <code>os.path.join</code> works over a set of strings.<br /> Therefore, in the first case you request a list; in the second, you request directly the strings.</p> <p>In other terms, the <strong>expressiveness</strong> of the interface should be the main guideline for choosing the way parameters should be passed.</p>
0
2009-07-16T10:48:48Z
[ "python", "api", "varargs" ]
is it required to give path after installation MySQL db for Python 2.6
1,136,676
<p>I am using Python 2.6.1, MySQL4.0 in Windows platform and I have successfully installed MySQLdb.</p> <p>Do we need to set any path for my python code and MySQLdb to successful run my application? Without any setting paths (in my code I am importing MySQLdb) I am getting <strong>No module named MySQLdb</strong> error is coming and I am not able to move further.</p>
1
2009-07-16T10:20:42Z
1,136,692
<p>How did you install MySQLdb? This sounds like your MySQLdb module is not within your PYTHONPATH which indicates some inconsistancy between how you installed Python itself and how you installed MySQLdb.</p> <p>Or did you perhaps install a MySQLdb binary that was not targeted for your version of Python? Modules are normally put into version-dependant folders.</p>
0
2009-07-16T10:23:48Z
[ "python", "mysql" ]
is it required to give path after installation MySQL db for Python 2.6
1,136,676
<p>I am using Python 2.6.1, MySQL4.0 in Windows platform and I have successfully installed MySQLdb.</p> <p>Do we need to set any path for my python code and MySQLdb to successful run my application? Without any setting paths (in my code I am importing MySQLdb) I am getting <strong>No module named MySQLdb</strong> error is coming and I am not able to move further.</p>
1
2009-07-16T10:20:42Z
1,136,842
<p>no, it is generally not required (not for good mannered modules like MySQLdb). </p> <p>did you check my answer to your previous question <a href="http://stackoverflow.com/questions/1135625/connecting-python-2-6-1-with-mysqldb">http://stackoverflow.com/questions/1135625/connecting-python-2-6-1-with-mysqldb</a></p>
0
2009-07-16T10:59:49Z
[ "python", "mysql" ]
What does python sys.intern do, and when should it be used?
1,136,826
<p>I came across <a href="http://stackoverflow.com/questions/327223/">this question</a> about memory management of dictionaries, which mentions the <strong>intern</strong> function. What exactly does it do, and when would it be used?</p> <p>To give an example:</p> <p>If I have a set called <strong>seen</strong>, that contains tuples in the form (string1,string2), which I use to check for duplicates, would storing (intern(string1),intern(string2)) improve performance w.r.t. memory or speed? </p>
27
2009-07-16T10:57:00Z
1,136,841
<p>It returns a canonical instance of the string.</p> <p>Therefore if you have many string instances that are equal you save memory, and in addition you can also compare canonicalized strings by identity instead of equality which is faster.</p>
4
2009-07-16T10:59:36Z
[ "python", "memory", "memory-management", "python-3.x" ]
What does python sys.intern do, and when should it be used?
1,136,826
<p>I came across <a href="http://stackoverflow.com/questions/327223/">this question</a> about memory management of dictionaries, which mentions the <strong>intern</strong> function. What exactly does it do, and when would it be used?</p> <p>To give an example:</p> <p>If I have a set called <strong>seen</strong>, that contains tuples in the form (string1,string2), which I use to check for duplicates, would storing (intern(string1),intern(string2)) improve performance w.r.t. memory or speed? </p>
27
2009-07-16T10:57:00Z
1,136,852
<p><em>From the <a href="http://docs.python.org/3.2/library/sys.html?highlight=sys.intern#sys.intern">Python 3</a> documentation</em>:</p> <pre><code>sys.intern(string) </code></pre> <blockquote> <p>Enter string in the table of “interned” strings and return the interned string – which is string itself or a copy. Interning strings is useful to gain a little performance on dictionary lookup – if the keys in a dictionary are interned, and the lookup key is interned, the key comparisons (after hashing) can be done by a pointer compare instead of a string compare. Normally, the names used in Python programs are automatically interned, and the dictionaries used to hold module, class or instance attributes have interned keys.</p> <p>Interned strings are not immortal; you must keep a reference to the return value of intern() around to benefit from it.</p> </blockquote> <p><em>Clarification</em>:</p> <p>As the documentation suggests, the <code>sys.intern</code> function is intended to be used for <strong>performance optimization</strong>.</p> <p>The <code>sys.intern</code> function maintains a table of <strong>interned</strong> strings. When you attempt to intern a string, the function looks it up in the table and:</p> <ol> <li><p>If the string does not exists (hasn't been interned yet) the function saves it in the table and returns it from the interned strings table.</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; a = sys.intern('why do pangolins dream of quiche') &gt;&gt;&gt; a 'why do pangolins dream of quiche' </code></pre> <p>In the above example, <code>a</code> holds the interned string. Even though it is not visible, the <code>sys.intern</code> function has saved the <code>'why do pangolins dream of quiche'</code> string object in the interned strings table.</p></li> <li><p>If the string exists (has been interned) the function returns it from the interned strings table.</p> <pre><code>&gt;&gt;&gt; b = sys.intern('why do pangolins dream of quiche') &gt;&gt;&gt; b 'why do pangolins dream of quiche' </code></pre> <p>Even though it is not immediately visible, because the string <code>'why do pangolins dream of quiche'</code> has been interned before, <code>b</code> holds now the same string object as <code>a</code>.</p> <pre><code>&gt;&gt;&gt; b is a True </code></pre> <p>If we create the same string without using intern, we end up with two different string objects that have the same value.</p> <pre><code>&gt;&gt;&gt; c = 'why do pangolins dream of quiche' &gt;&gt;&gt; c is a False &gt;&gt;&gt; c is b False </code></pre></li> </ol> <p>By using <code>sys.intern</code> you ensure that you never create two string objects that have the same value—when you request the creation of a second string object with the same value as an existing string object, you receive a reference to the pre-existing string object. This way, you are <strong>saving memory</strong>. Also, string objects comparison is now <strong>very efficient</strong> because it is carried out by comparing the memory addresses of the two string objects instead of their content.</p>
35
2009-07-16T11:02:23Z
[ "python", "memory", "memory-management", "python-3.x" ]
What does python sys.intern do, and when should it be used?
1,136,826
<p>I came across <a href="http://stackoverflow.com/questions/327223/">this question</a> about memory management of dictionaries, which mentions the <strong>intern</strong> function. What exactly does it do, and when would it be used?</p> <p>To give an example:</p> <p>If I have a set called <strong>seen</strong>, that contains tuples in the form (string1,string2), which I use to check for duplicates, would storing (intern(string1),intern(string2)) improve performance w.r.t. memory or speed? </p>
27
2009-07-16T10:57:00Z
1,136,872
<p>They weren't talking about keyword <code>intern</code> because there is no such thing in Python. They were talking about <a href="http://docs.python.org/library/functions.html?highlight=intern#intern" rel="nofollow">non-essential built-in function <code>intern</code></a>. Which in py3k has been moved to <a href="http://docs.python.org/3.1/library/sys.html?highlight=sys#sys.intern" rel="nofollow"><code>sys.intern</code></a>. Docs have an exhaustive description.</p>
9
2009-07-16T11:06:19Z
[ "python", "memory", "memory-management", "python-3.x" ]
What does python sys.intern do, and when should it be used?
1,136,826
<p>I came across <a href="http://stackoverflow.com/questions/327223/">this question</a> about memory management of dictionaries, which mentions the <strong>intern</strong> function. What exactly does it do, and when would it be used?</p> <p>To give an example:</p> <p>If I have a set called <strong>seen</strong>, that contains tuples in the form (string1,string2), which I use to check for duplicates, would storing (intern(string1),intern(string2)) improve performance w.r.t. memory or speed? </p>
27
2009-07-16T10:57:00Z
1,137,293
<p>Essentially intern looks up (or stores if not present) the string in a collection of interned strings, so all interned instances will share the same identity. You trade the one-time cost of looking up this string for faster comparisons (the compare can return True after just checking for identity, rather than having to compare each character), and reduced memory usage.</p> <p>However, python will automatically intern strings that are small, or look like identifiers, so you may find you get no improvement because your strings are already being interned behind the scenes. For example:</p> <pre><code>&gt;&gt;&gt; a = 'abc'; b = 'abc' &gt;&gt;&gt; a is b True </code></pre> <p>In the past, one disadvantage was that interned strings were permanent. Once interned, the string memory was never freed even after all references were dropped. I think this is no longer the case for more recent vesions of python though.</p>
15
2009-07-16T12:39:19Z
[ "python", "memory", "memory-management", "python-3.x" ]
What does python sys.intern do, and when should it be used?
1,136,826
<p>I came across <a href="http://stackoverflow.com/questions/327223/">this question</a> about memory management of dictionaries, which mentions the <strong>intern</strong> function. What exactly does it do, and when would it be used?</p> <p>To give an example:</p> <p>If I have a set called <strong>seen</strong>, that contains tuples in the form (string1,string2), which I use to check for duplicates, would storing (intern(string1),intern(string2)) improve performance w.r.t. memory or speed? </p>
27
2009-07-16T10:57:00Z
18,105,231
<p>This idea seems around us in several languages, including Python, Java etc.</p> <p><a href="http://en.wikipedia.org/wiki/String_interning" rel="nofollow">String Interning</a></p>
-2
2013-08-07T13:50:23Z
[ "python", "memory", "memory-management", "python-3.x" ]
What is the correct way to document a **kwargs parameter?
1,137,161
<p>I'm using <a href="http://sphinx.pocoo.org">sphinx</a> and the autodoc plugin to generate API documentation for my Python modules. Whilst I can see how to nicely document specific parameters, I cannot find an example of how to document a <code>**kwargs</code> parameter.</p> <p>Does anyone have a good example of a clear way to document these?</p>
32
2009-07-16T12:18:43Z
1,137,623
<p>I think <a href="http://docs.python.org/library/subprocess.html" rel="nofollow"><code>subprocess</code>-module's docs</a> is a good example. Give an exhaustive list of all parameters for a <a href="http://docs.python.org/2/library/subprocess.html#subprocess.Popen" rel="nofollow">top/parent class</a>. Then just refer to that list for all other occurrences of <code>**kwargs</code>.</p>
11
2009-07-16T13:32:54Z
[ "python", "documentation", "python-sphinx" ]
What is the correct way to document a **kwargs parameter?
1,137,161
<p>I'm using <a href="http://sphinx.pocoo.org">sphinx</a> and the autodoc plugin to generate API documentation for my Python modules. Whilst I can see how to nicely document specific parameters, I cannot find an example of how to document a <code>**kwargs</code> parameter.</p> <p>Does anyone have a good example of a clear way to document these?</p>
32
2009-07-16T12:18:43Z
16,420,859
<p>If anyone else is looking for some valid syntax.. Here's an example docstring. This is just how I did it, I hope it's useful to you, but I can't claim that it's compliant with anything in particular.</p> <pre><code>def bar(x=True, y=False): """ Just some silly bar function. :Parameters: - `x` (`bool`) - dummy description for x - `y` (`string`) - dummy description for y :return: (`string`) concatenation of x and y. """ return str(x) + y def foo (a, b, **kwargs): """ Do foo on a, b and some other objects. :Parameters: - `a` (`int`) - A number. - `b` (`int`, `string`) - Another number, or maybe a string. - `\**kwargs` - remaining keyword arguments are passed to `bar` :return: Success :rtype: `bool` """ return len(str(a) + str(b) + bar(**kwargs)) &gt; 20 </code></pre>
5
2013-05-07T13:53:34Z
[ "python", "documentation", "python-sphinx" ]
What is the correct way to document a **kwargs parameter?
1,137,161
<p>I'm using <a href="http://sphinx.pocoo.org">sphinx</a> and the autodoc plugin to generate API documentation for my Python modules. Whilst I can see how to nicely document specific parameters, I cannot find an example of how to document a <code>**kwargs</code> parameter.</p> <p>Does anyone have a good example of a clear way to document these?</p>
32
2009-07-16T12:18:43Z
21,056,959
<p>There is a <a href="http://pythonhosted.org/an_example_pypi_project/sphinx.html#full-code-exampl" rel="nofollow">doctstring example</a> for Sphinx in their documentation. Specifically they show the following: </p> <pre><code>ef public_fn_with_googley_docstring(name, state=None): """This function does something. Args: name (str): The name to use. Kwargs: state (bool): Current state to be in. Returns: int. The return code:: 0 -- Success! 1 -- No good. 2 -- Try again. Raises: AttributeError, KeyError A really great idea. A way you might use me is &gt;&gt;&gt; print public_fn_with_googley_docstring(name='foo', state=None) 0 BTW, this always returns 0. **NEVER** use with :class:`MyPublicClass`. """ return 0 </code></pre> <p>Though you asked about <a href="/questions/tagged/sphinx" class="post-tag" title="show questions tagged &#39;sphinx&#39;" rel="tag">sphinx</a> explicitly, I would also point to the <a href="http://google-styleguide.googlecode.com/svn/trunk/pyguide.html" rel="nofollow">Google Python Style Guide</a>. Their docstring example seems to imply that they don't call out kwargs specifically. (other_silly_variable=None) </p> <pre><code>def fetch_bigtable_rows(big_table, keys, other_silly_variable=None): """Fetches rows from a Bigtable. Retrieves rows pertaining to the given keys from the Table instance represented by big_table. Silly things may happen if other_silly_variable is not None. Args: big_table: An open Bigtable Table instance. keys: A sequence of strings representing the key of each table row to fetch. other_silly_variable: Another optional variable, that has a much longer name than the other args, and which does nothing. Returns: A dict mapping keys to the corresponding table row data fetched. Each row is represented as a tuple of strings. For example: {'Serak': ('Rigel VII', 'Preparer'), 'Zim': ('Irk', 'Invader'), 'Lrrr': ('Omicron Persei 8', 'Emperor')} If a key from the keys argument is missing from the dictionary, then that row was not found in the table. Raises: IOError: An error occurred accessing the bigtable.Table object. """ pass </code></pre> <p>A-B-B has a question about the accepted answer of referencing the subprocess management documentation. If you import a module, you can quickly see the module docstrings via inspect.getsource. </p> <p>An example from the python interpreter using Silent Ghost's recommendation: </p> <pre><code>&gt;&gt;&gt; import subprocess &gt;&gt;&gt; import inspect &gt;&gt;&gt; import print inspect.getsource(subprocess) </code></pre> <p>Of course you can also view the module documentation via help function. For example help(subprocess) </p> <p>I'm not personally a fan of the subprocess docstring for kwargs as an example, but like the Google example it doesn't list kwargs seperately as shown in the Sphinx documentation example. </p> <pre><code>def call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) """ return Popen(*popenargs, **kwargs).wait() </code></pre> <p>I'm including this answer to A-B-B's question because it's worth noting that you can review any module's source or documentation this way for insights and inspiration for commenting your code.</p>
4
2014-01-11T00:30:49Z
[ "python", "documentation", "python-sphinx" ]
What is the correct way to document a **kwargs parameter?
1,137,161
<p>I'm using <a href="http://sphinx.pocoo.org">sphinx</a> and the autodoc plugin to generate API documentation for my Python modules. Whilst I can see how to nicely document specific parameters, I cannot find an example of how to document a <code>**kwargs</code> parameter.</p> <p>Does anyone have a good example of a clear way to document these?</p>
32
2009-07-16T12:18:43Z
27,724,915
<p>After finding this question I settled on the following, which is valid Sphinx and works fairly well:</p> <pre><code>def some_function(first, second="two", **kwargs): r"""Fetches and returns this thing :param first: The first parameter :type first: ``int`` :param second: The second parameter :type second: ``str`` :param \**kwargs: See below :Keyword Arguments: * *extra* (``list``) -- Extra stuff * *supplement* (``dict``) -- Additional content """ </code></pre> <p>The <code>r"""..."""</code> is required to make this a "raw" docstring and thus keep the <code>\*</code> intact (for Sphinx to pick up as a literal <code>*</code> and not the start of "emphasis").</p> <p>The chosen formatting (bulleted list with parenthesized type and m-dash-separated description) is simply to match the automated formatting provided by Sphinx.</p> <p>Once you've gone to this effort of making the "Keyword Arguments" section look like the default "Parameters" section, it seems like it might be easier to roll your own parameters section from the outset (as per some of the other answers), but as a proof of concept this is one way to achieve a nice look for supplementary <code>**kwargs</code> if you're already using Sphinx.</p>
6
2014-12-31T18:25:47Z
[ "python", "documentation", "python-sphinx" ]
What is the correct way to document a **kwargs parameter?
1,137,161
<p>I'm using <a href="http://sphinx.pocoo.org">sphinx</a> and the autodoc plugin to generate API documentation for my Python modules. Whilst I can see how to nicely document specific parameters, I cannot find an example of how to document a <code>**kwargs</code> parameter.</p> <p>Does anyone have a good example of a clear way to document these?</p>
32
2009-07-16T12:18:43Z
32,273,299
<p><strong>Google Style docstrings parsed by Sphinx</strong></p> <p>Disclaimer: not tested.</p> <p>From this cutout of the <a href="http://sphinx-doc.org/latest/ext/example_google.html#example-google" rel="nofollow">sphinx docstring example</a>, the <code>*args</code> and <code>**kwargs</code> are left <strong>unexpanded</strong>:</p> <pre><code>def module_level_function(param1, param2=None, *args, **kwargs): """ ... Args: param1 (int): The first parameter. param2 (Optional[str]): The second parameter. Defaults to None. Second line of description should be indented. *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. </code></pre> <p>I would <strong>suggest</strong> the following solution for compactness:</p> <pre><code> """ Args: param1 (int): The first parameter. param2 (Optional[str]): The second parameter. Defaults to None. Second line of description should be indented. *param3 (int): descritpion *param4 (str): ... **key1 (int): description **key2 (int): description ... </code></pre> <p>Notice how, <code>Optional</code> is not required for <code>**key</code> arguments. </p> <p><strong>Otherwise</strong>, you can try to explicitly list the *args under <code>Other Parameters</code> and <code>**kwargs</code> under the <code>Keyword Args</code> (see parsed <a href="http://sphinxcontrib-napoleon.readthedocs.org/en/latest/index.html#sections" rel="nofollow">sections</a>):</p> <pre><code> """ Args: param1 (int): The first parameter. param2 (Optional[str]): The second parameter. Defaults to None. Second line of description should be indented. Other Parameters: param3 (int): descritpion param4 (str): ... Keyword Args: key1 (int): description key2 (int): description ... </code></pre>
2
2015-08-28T14:22:05Z
[ "python", "documentation", "python-sphinx" ]
Using python scipy.weave inline with ctype variables?
1,137,852
<p>I am trying to pass a ctype variable to inline c code using scipy.weave.inline. One would think this would be simple. Documentation is good when doing it with normal python object types, however, they have a lot more features than I need, and It makes more sense to me to use ctypes when working with C. I am unsure, however, where my error is.</p> <pre><code>from scipy.weave import inline from ctypes import * def test(): y = c_float()*50 x = pointer(y) code = """ #line 120 "laplace.py" (This is only useful for debugging) int i; for (i=0; i &lt; 50; i++) { x[i] = 1; } """ inline(code, [x], compiler = 'gcc') return y output = test() pi = pointer(output) print pi[0] </code></pre>
4
2009-07-16T14:07:24Z
1,336,093
<p>scipy.weave does not know anything about ctypes. Inputs are restricted to most of the basic builtin types, numpy arrays, wxPython objects, VTK objects, and SWIG wrapped objects. You can add your own converter code, though. There is currently not much documentation on this, but you can look at the <a href="http://svn.scipy.org/svn/scipy/trunk/scipy/weave/swig2%5Fspec.py" rel="nofollow">SWIG implementation</a> as an instructive example.</p>
4
2009-08-26T16:47:50Z
[ "python", "scipy", "inline-code" ]
Recommended Python cryptographic module?
1,137,874
<p>I've been exploring what cryptographic modules are available to Python, and I've found 3: ezPyCrypt, yawPyCrypt and KeyCzar (which actually supports a few languages, but Python is included amongst them). The first two rely on the PyCrypto module.</p> <p>Are there choices I am missing? Is there a clear front-runner for ease and features or does it simply come down to a manner of one's comfort level?</p> <p>I'm currently leaning towards KeyCzar, with ezPyCrypt close behind.</p> <p>I would be using the library for digital signature signing and verification, and potentially for key creation (although I won't cry if I have to make a call to something else for that functionality).</p> <p>I am using Python 3.x and have access to GPG.</p>
25
2009-07-16T14:09:39Z
1,137,912
<p>If you are in an environment which includes GnuPG and Python >= 2.4, then you could also consider a tool such as <a href="http://code.google.com/p/python-gnupg/">python-gnupg</a>. (Disclaimer: I'm the maintainer of this project.) It leaves the heavy lifting to <code>gpg</code> and provides a fairly straightforward API.</p> <p>Overview of API:</p> <pre> >>> import gnupg >>> gpg = gnupg.GPG(gnupghome='/path/to/keyring/directory') >>> gpg.list_keys() [{ ... 'fingerprint': 'F819EE7705497D73E3CCEE65197D5DAC68F1AAB2', 'keyid': '197D5DAC68F1AAB2', 'length': '1024', 'type': 'pub', 'uids': ['', 'Gary Gross (A test user) ']}, { ... 'fingerprint': '37F24DD4B918CC264D4F31D60C5FEFA7A921FC4A', 'keyid': '0C5FEFA7A921FC4A', 'length': '1024', ... 'uids': ['', 'Danny Davis (A test user) ']}] >>> encrypted = gpg.encrypt("Hello, world!", ['0C5FEFA7A921FC4A']) >>> str(encrypted) '-----BEGIN PGP MESSAGE-----\nVersion: GnuPG v1.4.9 (GNU/Linux)\n \nhQIOA/6NHMDTXUwcEAf ... -----END PGP MESSAGE-----\n' >>> decrypted = gpg.decrypt(str(encrypted), passphrase='secret') >>> str(decrypted) 'Hello, world!' >>> signed = gpg.sign("Goodbye, world!", passphrase='secret') >>> verified = verified = gpg.verify(str(signed)) >>> print "Verified" if verified else "Not verified" 'Verified' </pre>
12
2009-07-16T14:15:34Z
[ "python", "cryptography" ]
Recommended Python cryptographic module?
1,137,874
<p>I've been exploring what cryptographic modules are available to Python, and I've found 3: ezPyCrypt, yawPyCrypt and KeyCzar (which actually supports a few languages, but Python is included amongst them). The first two rely on the PyCrypto module.</p> <p>Are there choices I am missing? Is there a clear front-runner for ease and features or does it simply come down to a manner of one's comfort level?</p> <p>I'm currently leaning towards KeyCzar, with ezPyCrypt close behind.</p> <p>I would be using the library for digital signature signing and verification, and potentially for key creation (although I won't cry if I have to make a call to something else for that functionality).</p> <p>I am using Python 3.x and have access to GPG.</p>
25
2009-07-16T14:09:39Z
1,137,959
<p>How about <a href="http://www.pycrypto.org/" rel="nofollow">PyCrypto</a> (formerly <a href="http://www.amk.ca/python/code/crypto.html" rel="nofollow">http://www.amk.ca/python/code/crypto.html</a>)??</p>
1
2009-07-16T14:21:45Z
[ "python", "cryptography" ]
Recommended Python cryptographic module?
1,137,874
<p>I've been exploring what cryptographic modules are available to Python, and I've found 3: ezPyCrypt, yawPyCrypt and KeyCzar (which actually supports a few languages, but Python is included amongst them). The first two rely on the PyCrypto module.</p> <p>Are there choices I am missing? Is there a clear front-runner for ease and features or does it simply come down to a manner of one's comfort level?</p> <p>I'm currently leaning towards KeyCzar, with ezPyCrypt close behind.</p> <p>I would be using the library for digital signature signing and verification, and potentially for key creation (although I won't cry if I have to make a call to something else for that functionality).</p> <p>I am using Python 3.x and have access to GPG.</p>
25
2009-07-16T14:09:39Z
1,138,183
<p><a href="http://code.google.com/p/pycrypt/">pycrypt</a> is actually a simple AES encrypt/decrypt module built on top of <a href="http://www.pycrypto.org/">pycrypto</a> like other modules you mention -- note that the latter is transitioning to the pycrypto.org URL as it's changing maintainers, and stable versions and docs are still at the original author's <a href="http://www.amk.ca/python/code/crypto">site</a>. In addition to the easier-to-use wrappers you mention, one plus of pycrypto is that a pure-python <a href="http://code.google.com/appengine/docs/python/tools/libraries.html#PyCrypto">subset</a> of it is supplied with Google's App Engine, so getting familiar with it would be useful if you ever want to deploy any code there.</p> <p>The major alternative (another powerful and complex project, like pycrypto) is <a href="https://launchpad.net/pyopenssl">pyopenssl</a>, which is a fairly regular wrapping (a "thin wrapper", as the author describes it) of <a href="http://www.openssl.org/">OpenSSL</a> (that may be a plus if you're used to coding in C with calls to OpenSSL). An alternative packaging that's complete (comes with the needed libraries) and possibly legally safer (excludes parts on which there are patent disputes or doubts) is distributed by <a href="http://www.egenix.com/products/python/pyOpenSSL/">egenix</a>.</p> <p>Both main projects (pycrypto and pyopenssl) went through long periods of more or less inactivity as the original authors went on to other things, but both are actively developed and maintained again, which is always a good sign.</p> <p>I am not aware of easy-to-use wrappers on top of pyopenssl (there most likely are, but they haven't been publicized like those on top of pycrypto) and so, if as it seems you do care about ease of use and aren't looking to write wrappers yourself, the ones on top of pycrypto appear to be a better choice.</p>
7
2009-07-16T14:51:25Z
[ "python", "cryptography" ]
Recommended Python cryptographic module?
1,137,874
<p>I've been exploring what cryptographic modules are available to Python, and I've found 3: ezPyCrypt, yawPyCrypt and KeyCzar (which actually supports a few languages, but Python is included amongst them). The first two rely on the PyCrypto module.</p> <p>Are there choices I am missing? Is there a clear front-runner for ease and features or does it simply come down to a manner of one's comfort level?</p> <p>I'm currently leaning towards KeyCzar, with ezPyCrypt close behind.</p> <p>I would be using the library for digital signature signing and verification, and potentially for key creation (although I won't cry if I have to make a call to something else for that functionality).</p> <p>I am using Python 3.x and have access to GPG.</p>
25
2009-07-16T14:09:39Z
1,384,831
<p>I've just done such a survey last week and adopted M2Crypto that seems to be the most advanced wrapper today above openssl (found it in several recommandation lists while googling). I also tried pycrypto but it miss certificates management and standard key file format management that M2Crypto has (with pycrypto you have to pickle/unpicle your keys or write your own key manager for common formats).</p> <p>I found M2Crypto was quite easy to use and was quicly able to develop what I needed (a signed and encrypted package format).</p> <p>However I recommand to download full package, not just easy installing it, because in the package you also get nice exemples (look at demo directory).</p> <p>Here is the link <a href="http://pypi.python.org/pypi/M2Crypto/0.20.1" rel="nofollow">http://pypi.python.org/pypi/M2Crypto/0.20.1</a></p> <p>A drawback could be that you are using python 3.0, I'm stuck with 2.5 at job (hopefully 2.6 soon) and don't know if M2Crypto works with python 3.0</p> <p>I've not much practice with it yet, put if you have specific problems with it just ask here. Someone may answer.</p>
2
2009-09-06T04:00:23Z
[ "python", "cryptography" ]
Recommended Python cryptographic module?
1,137,874
<p>I've been exploring what cryptographic modules are available to Python, and I've found 3: ezPyCrypt, yawPyCrypt and KeyCzar (which actually supports a few languages, but Python is included amongst them). The first two rely on the PyCrypto module.</p> <p>Are there choices I am missing? Is there a clear front-runner for ease and features or does it simply come down to a manner of one's comfort level?</p> <p>I'm currently leaning towards KeyCzar, with ezPyCrypt close behind.</p> <p>I would be using the library for digital signature signing and verification, and potentially for key creation (although I won't cry if I have to make a call to something else for that functionality).</p> <p>I am using Python 3.x and have access to GPG.</p>
25
2009-07-16T14:09:39Z
18,034,210
<p><a href="https://pypi.python.org/pypi/pycrypto" rel="nofollow">PyCrypto</a> is my choice atm (latest pypi update 2012-05-24) and the source code is hosted on GitHub: <a href="https://github.com/dlitz/pycrypto" rel="nofollow">https://github.com/dlitz/pycrypto</a>. It can run pure Python math or use <a href="http://gmplib.org/" rel="nofollow">libgmp</a> (you will need <code>sudo apt-get install libgmp-dev</code> on Debian to enable the latest).</p> <p><a href="https://pypi.python.org/pypi/M2Crypto" rel="nofollow">M2Crypto</a> is a wrapper for OpenSSL (latest pypi update 2011-01-15), source code at <a href="http://svn.osafoundation.org/m2crypto/" rel="nofollow">http://svn.osafoundation.org/m2crypto/</a>.</p> <p><a href="https://pypi.python.org/pypi/gnupg" rel="nofollow">gnupg</a> (updated 2013-06-05), see <a href="http://stackoverflow.com/questions/1137874/recommended-python-cryptographic-module#1137912">Vinay Sajip's answer</a>. There is a <a href="https://pypi.python.org/pypi/gnupg" rel="nofollow">patched fork</a> (updated 2013-07-31) hosted at <a href="https://github.com/isislovecruft/python-gnupg" rel="nofollow">https://github.com/isislovecruft/python-gnupg</a></p> <p>Other alternatives are mentioned by <a href="http://stackoverflow.com/questions/1137874/recommended-python-cryptographic-module#1138183">Alex Martelli</a></p> <p>EDIT: critics of existing crypto packages and references to some new ones <a href="https://news.ycombinator.com/item?id=6194102" rel="nofollow">https://news.ycombinator.com/item?id=6194102</a></p>
2
2013-08-03T15:06:46Z
[ "python", "cryptography" ]
Recommended Python cryptographic module?
1,137,874
<p>I've been exploring what cryptographic modules are available to Python, and I've found 3: ezPyCrypt, yawPyCrypt and KeyCzar (which actually supports a few languages, but Python is included amongst them). The first two rely on the PyCrypto module.</p> <p>Are there choices I am missing? Is there a clear front-runner for ease and features or does it simply come down to a manner of one's comfort level?</p> <p>I'm currently leaning towards KeyCzar, with ezPyCrypt close behind.</p> <p>I would be using the library for digital signature signing and verification, and potentially for key creation (although I won't cry if I have to make a call to something else for that functionality).</p> <p>I am using Python 3.x and have access to GPG.</p>
25
2009-07-16T14:09:39Z
22,033,391
<p>A new cryptography library for Python has been in rapid development for a few months now. The 0.2.1 release just happened a few days ago. </p> <p><a href="https://cryptography.io/en/latest/">https://cryptography.io/en/latest/</a></p> <p>It is mainly a CFFI wrapper around existing C libraries such as OpenSSL. It is distributed as a pure python module and supports CPython versions 2.6 - 3.3 as well as PyPy. It is also the upstream of the refactored pyOpenSSL package. </p> <p>It aims to expose high-level "recipes" that makes cryptography as idiot-proof as possible as well as primitives that should only be used with the appropriate caution. Symmetric algorithms (including AES-GCM) is very well supported and asymmetric algorithms such as RSA and DSA should be coming in the next few releases. Other notable algorithms that are supported includes PBKDF2, HKDF, HOTP and TOTP.</p>
12
2014-02-26T06:20:09Z
[ "python", "cryptography" ]
Recommended Python cryptographic module?
1,137,874
<p>I've been exploring what cryptographic modules are available to Python, and I've found 3: ezPyCrypt, yawPyCrypt and KeyCzar (which actually supports a few languages, but Python is included amongst them). The first two rely on the PyCrypto module.</p> <p>Are there choices I am missing? Is there a clear front-runner for ease and features or does it simply come down to a manner of one's comfort level?</p> <p>I'm currently leaning towards KeyCzar, with ezPyCrypt close behind.</p> <p>I would be using the library for digital signature signing and verification, and potentially for key creation (although I won't cry if I have to make a call to something else for that functionality).</p> <p>I am using Python 3.x and have access to GPG.</p>
25
2009-07-16T14:09:39Z
24,758,365
<p>Another crypto library to consider is <a href="http://www.pycryptodome.org/" rel="nofollow">PyCryptodome</a>, a fork of PyCrypto with PyPy support and a few more primitives (SHA-3, Salsa20, scrypt, etc).</p>
5
2014-07-15T12:35:24Z
[ "python", "cryptography" ]
Recommended Python cryptographic module?
1,137,874
<p>I've been exploring what cryptographic modules are available to Python, and I've found 3: ezPyCrypt, yawPyCrypt and KeyCzar (which actually supports a few languages, but Python is included amongst them). The first two rely on the PyCrypto module.</p> <p>Are there choices I am missing? Is there a clear front-runner for ease and features or does it simply come down to a manner of one's comfort level?</p> <p>I'm currently leaning towards KeyCzar, with ezPyCrypt close behind.</p> <p>I would be using the library for digital signature signing and verification, and potentially for key creation (although I won't cry if I have to make a call to something else for that functionality).</p> <p>I am using Python 3.x and have access to GPG.</p>
25
2009-07-16T14:09:39Z
25,865,136
<p>Keyczar is cool, but it lacks OAEP|PKCS padding which is only avaliable in Java version. <a href="https://code.google.com/p/keyczar/wiki/KeyczarTool" rel="nofollow">https://code.google.com/p/keyczar/wiki/KeyczarTool</a></p> <p>Also, at the moment it lacks password based encryption which is avaliable in C++. <a href="https://code.google.com/p/keyczar/issues/detail?id=149&amp;colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Implementation%20Summary" rel="nofollow">https://code.google.com/p/keyczar/issues/detail?id=149&amp;colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Implementation%20Summary</a></p>
0
2014-09-16T09:25:52Z
[ "python", "cryptography" ]
Get first non-empty string from a list in python
1,138,024
<p>In Python I have a list of strings, some of which may be the empty string. What's the best way to get the first non-empty string?</p>
8
2009-07-16T14:30:41Z
1,138,036
<p>To remove all empty strings,</p> <p><code>[s for s in list_of_strings if s]</code></p> <p>To get the first non-empty string, simply create this list and get the first element, or use the lazy method as suggested by wuub.</p>
5
2009-07-16T14:33:08Z
[ "python", "string", "list" ]
Get first non-empty string from a list in python
1,138,024
<p>In Python I have a list of strings, some of which may be the empty string. What's the best way to get the first non-empty string?</p>
8
2009-07-16T14:30:41Z
1,138,042
<pre><code>def get_nonempty(list_of_strings): for s in list_of_strings: if s: return s </code></pre>
3
2009-07-16T14:33:58Z
[ "python", "string", "list" ]
Get first non-empty string from a list in python
1,138,024
<p>In Python I have a list of strings, some of which may be the empty string. What's the best way to get the first non-empty string?</p>
8
2009-07-16T14:30:41Z
1,138,051
<pre><code>next(s for s in list_of_string if s) </code></pre> <p>Edit: py3k proof version as advised by Stephan202 in comments, thanks. </p>
15
2009-07-16T14:35:12Z
[ "python", "string", "list" ]
Get first non-empty string from a list in python
1,138,024
<p>In Python I have a list of strings, some of which may be the empty string. What's the best way to get the first non-empty string?</p>
8
2009-07-16T14:30:41Z
1,138,151
<p>to get the first non empty string in a list, you just have to loop over it and check if its not empty. that's all there is to it.</p> <pre><code>arr = ['','',2,"one"] for i in arr: if i: print i break </code></pre>
0
2009-07-16T14:47:29Z
[ "python", "string", "list" ]
Get first non-empty string from a list in python
1,138,024
<p>In Python I have a list of strings, some of which may be the empty string. What's the best way to get the first non-empty string?</p>
8
2009-07-16T14:30:41Z
1,138,260
<p>Here's a short way:</p> <pre><code>filter(None, list_of_strings)[0] </code></pre> <p>EDIT:</p> <p>Here's a slightly longer way that is better:</p> <pre><code>from itertools import ifilter ifilter(None, list_of_strings).next() </code></pre>
2
2009-07-16T15:00:57Z
[ "python", "string", "list" ]
Get first non-empty string from a list in python
1,138,024
<p>In Python I have a list of strings, some of which may be the empty string. What's the best way to get the first non-empty string?</p>
8
2009-07-16T14:30:41Z
1,138,534
<p>Based on your question I'll have to assume a lot, but to "get" the first non-empty string:</p> <pre><code>(i for i, s in enumerate(x) if s).next() </code></pre> <p>which returns its index in the list. The 'x' binding points to your list of strings.</p>
0
2009-07-16T15:46:56Z
[ "python", "string", "list" ]
Django Template Error : Template u'base.html' cannot be extended
1,138,106
<p>I get this error when I run a django app (<a href="http://github.com/bartTC/django-paste/tree" rel="nofollow">dpaste</a>)</p> <pre><code>Template error In template c:\python\projects\mycms\dpaste\templates\dpaste\base.html, error at line 1 Template u'base.html' cannot be extended, because it doesn't exist 1 {% extends "base.html" %} </code></pre> <p>But the <a href="http://github.com/bartTC/django-paste/blob/bc7445d7a3973684bc2641d1841332080c464f3e/dpaste/templates/dpaste/base.html" rel="nofollow">"base.html"</a> do exist in the template directory and it has this one line in it:</p> <pre><code>{% extends "base.html" %} </code></pre> <p>What is wrong with that?</p>
0
2009-07-16T14:42:20Z
1,138,130
<p>Your base.html template cannot extend itself. The problem lies there. Remove that line and replace it with valid html or other Django template tags (or extend some other template).</p>
3
2009-07-16T14:44:46Z
[ "python", "django", "django-templates" ]
Django Template Error : Template u'base.html' cannot be extended
1,138,106
<p>I get this error when I run a django app (<a href="http://github.com/bartTC/django-paste/tree" rel="nofollow">dpaste</a>)</p> <pre><code>Template error In template c:\python\projects\mycms\dpaste\templates\dpaste\base.html, error at line 1 Template u'base.html' cannot be extended, because it doesn't exist 1 {% extends "base.html" %} </code></pre> <p>But the <a href="http://github.com/bartTC/django-paste/blob/bc7445d7a3973684bc2641d1841332080c464f3e/dpaste/templates/dpaste/base.html" rel="nofollow">"base.html"</a> do exist in the template directory and it has this one line in it:</p> <pre><code>{% extends "base.html" %} </code></pre> <p>What is wrong with that?</p>
0
2009-07-16T14:42:20Z
1,138,131
<p>A template can't extend itself. </p>
1
2009-07-16T14:44:53Z
[ "python", "django", "django-templates" ]
Django Template Error : Template u'base.html' cannot be extended
1,138,106
<p>I get this error when I run a django app (<a href="http://github.com/bartTC/django-paste/tree" rel="nofollow">dpaste</a>)</p> <pre><code>Template error In template c:\python\projects\mycms\dpaste\templates\dpaste\base.html, error at line 1 Template u'base.html' cannot be extended, because it doesn't exist 1 {% extends "base.html" %} </code></pre> <p>But the <a href="http://github.com/bartTC/django-paste/blob/bc7445d7a3973684bc2641d1841332080c464f3e/dpaste/templates/dpaste/base.html" rel="nofollow">"base.html"</a> do exist in the template directory and it has this one line in it:</p> <pre><code>{% extends "base.html" %} </code></pre> <p>What is wrong with that?</p>
0
2009-07-16T14:42:20Z
2,491,667
<p>If you meant to say that:</p> <pre><code>{% extends "base.html" %} </code></pre> <p>is the only line in the including template, not the base template, then maybe your problem is that "base.html" is relative to the template root.</p> <p>So if in settings you have:</p> <pre><code>TEMPLATE_DIRS = ("/home/me/mysite/mytemplates") </code></pre> <p>and the including template is:</p> <pre><code>/home/me/mysite/mytemplates/myapp/page.html </code></pre> <p>and the base template is:</p> <pre><code>/home/me/mysite/mytemplates/myapp/base.html </code></pre> <p>then you want to use:</p> <pre><code>{% extends "myapp/base.html" %} </code></pre> <p>At least that's what my problem was when I found this page.</p>
0
2010-03-22T11:10:14Z
[ "python", "django", "django-templates" ]
Execution of script using Popen fails
1,138,111
<p>I need to execute a script in the background through a service.</p> <p>The service kicks off the script using Popen.</p> <pre><code>p = Popen('/path/to/script/script.py', shell=True) </code></pre> <p>Why doesn't the following script work when I include the file writes in the for loop?</p> <pre><code>#!/usr/bin/python import os import time def run(): fd = open('/home/dilleyjrr/testOutput.txt', 'w') fd.write('Start:\n') fd.flush() for x in (1,2,3,4,5): fd.write(x + '\n') fd.flush() time.sleep(1) fd.write('Done!!!!\n') fd.flush() fd.close() if __name__ == '__main__': run() </code></pre>
1
2009-07-16T14:42:42Z
1,138,149
<p>What error are you getting? It's hard to see the problem without the error. Is there anyway that the file is opened somewhere else?</p>
0
2009-07-16T14:47:07Z
[ "python", "mod-python", "popen" ]
Execution of script using Popen fails
1,138,111
<p>I need to execute a script in the background through a service.</p> <p>The service kicks off the script using Popen.</p> <pre><code>p = Popen('/path/to/script/script.py', shell=True) </code></pre> <p>Why doesn't the following script work when I include the file writes in the for loop?</p> <pre><code>#!/usr/bin/python import os import time def run(): fd = open('/home/dilleyjrr/testOutput.txt', 'w') fd.write('Start:\n') fd.flush() for x in (1,2,3,4,5): fd.write(x + '\n') fd.flush() time.sleep(1) fd.write('Done!!!!\n') fd.flush() fd.close() if __name__ == '__main__': run() </code></pre>
1
2009-07-16T14:42:42Z
1,138,261
<p>Here's your bug:</p> <pre><code>for x in (1,2,3,4,5): fd.write(x + '\n') </code></pre> <p>You cannot sum an int to a string. Use instead (e.g.)</p> <pre><code>for x in (1,2,3,4,5): fd.write('%s\n' % x) </code></pre>
1
2009-07-16T15:00:59Z
[ "python", "mod-python", "popen" ]
Python: Get Mount Point on Windows or Linux
1,138,383
<p>I need a function to determine if a directory is a mount point for a drive. I found this code already which works well for linux:</p> <pre><code>def getmount(path): path = os.path.abspath(path) while path != os.path.sep: if os.path.ismount(path): return path path = os.path.abspath(os.path.join(path, os.pardir)) return path </code></pre> <p>But I'm not sure how I would get this to work on windows. Can I just assume the mount point is the drive letter (e.g. C:)? I believe it is possible to have a network mount on windows so I'd like to be able to detect that mount as well.</p>
5
2009-07-16T15:20:01Z
1,138,411
<p>Windows didn't use to call them "mount points" [<strong>edit</strong>: it now does, see below!], and the two typical/traditional syntaxes you can find for them are either a drive letter, e.g. <code>Z:</code>, or else <code>\\hostname</code> (with two leading backslashes: escape carefully or use <code>r'...'</code> notation in Python fpr such literal strings).</p> <p><strong>edit</strong>: since NTFS 5.0 mount points are supported, but according to <a href="http://brainrack.wordpress.com/2008/05/28/broken-and-ill-documented-api-for-windows-mount-points/" rel="nofollow">this post</a> the API for them is in quite a state -- "broken and ill-documented", the post's title says. Maybe executing the microsoft-supplied <a href="http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/mountvol.mspx?mfr=true" rel="nofollow">mountvol.exe</a> is the least painful way -- <code>mountvol drive:path /L</code> should emit the mounted volume name for the specified path, or just <code>mountvol</code> such list all such mounts (I have to say "should" because I can't check right now). You can execute it with <code>subprocess.Popen</code> and check its output.</p>
3
2009-07-16T15:25:10Z
[ "python", "windows", "linux", "operating-system", "mount" ]
Python: Get Mount Point on Windows or Linux
1,138,383
<p>I need a function to determine if a directory is a mount point for a drive. I found this code already which works well for linux:</p> <pre><code>def getmount(path): path = os.path.abspath(path) while path != os.path.sep: if os.path.ismount(path): return path path = os.path.abspath(os.path.join(path, os.pardir)) return path </code></pre> <p>But I'm not sure how I would get this to work on windows. Can I just assume the mount point is the drive letter (e.g. C:)? I believe it is possible to have a network mount on windows so I'd like to be able to detect that mount as well.</p>
5
2009-07-16T15:20:01Z
1,139,594
<p>Do you want to find the mount point or just determine if it is a mountpoint?</p> <p>Regardless, as commented above, it is possible in WinXP to map a logical drive to a folder.</p> <p>See here for details: <a href="http://www.modzone.dk/forums/showthread.php?threadid=278" rel="nofollow">http://www.modzone.dk/forums/showthread.php?threadid=278</a></p> <p>I would try win32api.GetVolumeInformation</p> <pre><code>&gt;&gt;&gt; import win32api &gt;&gt;&gt; win32api.GetVolumeInformation("C:\\") ('LABEL', 1280075370, 255, 459007, 'NTFS') &gt;&gt;&gt; win32api.GetVolumeInformation("D:\\") ('CD LABEL', 2137801086, 110, 524293, 'CDFS') &gt;&gt;&gt; win32api.GetVolumeInformation("C:\\TEST\\") # same as D: ('CD LABEL', 2137801086, 110, 524293, 'CDFS') &gt;&gt;&gt; win32api.GetVolumeInformation("\\\\servername\\share\\") ('LABEL', -994499922, 255, 11, 'NTFS') &gt;&gt;&gt; win32api.GetVolumeInformation("C:\\WINDOWS\\") # not a mount point Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; pywintypes.error: (144, 'GetVolumeInformation', 'The directory is not a subdirectory of the root directory.') </code></pre>
3
2009-07-16T18:56:57Z
[ "python", "windows", "linux", "operating-system", "mount" ]
Python: Get Mount Point on Windows or Linux
1,138,383
<p>I need a function to determine if a directory is a mount point for a drive. I found this code already which works well for linux:</p> <pre><code>def getmount(path): path = os.path.abspath(path) while path != os.path.sep: if os.path.ismount(path): return path path = os.path.abspath(os.path.join(path, os.pardir)) return path </code></pre> <p>But I'm not sure how I would get this to work on windows. Can I just assume the mount point is the drive letter (e.g. C:)? I believe it is possible to have a network mount on windows so I'd like to be able to detect that mount as well.</p>
5
2009-07-16T15:20:01Z
6,835,904
<p>Here is some code to return the UNC path pointed to by a drive letter. I suppose there is a more slick way to do this, but I thought I'd contribute my small part.</p> <pre><code>import sys,os,string,re,win32file for ch in string.uppercase: # use all uppercase letters, one at a time dl = ch + ":" try: flds = win32file.QueryDosDevice(dl).split("\x00") except: continue if re.search('^\\\\Device\\\\LanmanRedirector\\\\',flds[0]): flds2 = flds[0].split(":") st = flds2[1] n = st.find("\\") path = st[n:] print(path) </code></pre>
0
2011-07-26T20:04:24Z
[ "python", "windows", "linux", "operating-system", "mount" ]
Add SMTP AUTH support to Python smtpd library... can't override the method?
1,138,425
<p>So, I wanted to extend the Python smtpd SMTPServer class so that it could handle SMTP AUTH connections. Seemed simple enough... </p> <p>So, it looked like I could just start like this: </p> <pre><code>def smtp_EHLO(self, arg): print 'got in arg: ', arg # do stuff here... </code></pre> <p>But for some reason, that never gets called. The Python smtpd library calls other similar methods like this:</p> <pre><code> method = None i = line.find(' ') if i &lt; 0: command = line.upper() arg = None else: command = line[:i].upper() arg = line[i+1:].strip() method = getattr(self, 'smtp_' + command, None) </code></pre> <p>Why won't it call my method? </p> <p>After that, I thought that I could probably just override the entire found_terminator(self): method, but that doesn't seem to work either. </p> <pre><code> def found_terminator(self): # I add this to my child class and it never gets called... </code></pre> <p>Am I doing something stupid or...? Maybe I just haven't woken up fully yet today...</p> <pre><code>import smtpd import asyncore class CustomSMTPServer(smtpd.SMTPServer): def smtp_EHLO(self, arg): print 'got in arg: ', arg def process_message(self, peer, mailfrom, rcpttos, data): print 'Receiving message from:', peer print 'Message addressed from:', mailfrom print 'Message addressed to :', rcpttos print 'Message length :', len(data) print 'HERE WE ARE MAN!' return # Implementation of base class abstract method def found_terminator(self): print 'THIS GOT CALLED RIGHT HERE!' line = EMPTYSTRING.join(self.__line) print &gt;&gt; DEBUGSTREAM, 'Data:', repr(line) self.__line = [] if self.__state == self.COMMAND: if not line: self.push('500 Error: bad syntax') return method = None i = line.find(' ') if i &lt; 0: command = line.upper() arg = None else: command = line[:i].upper() arg = line[i+1:].strip() method = getattr(self, 'smtp_' + command, None) print 'looking for: ', command print 'method is: ', method if not method: self.push('502 Error: command "%s" not implemented' % command) return method(arg) return else: if self.__state != self.DATA: self.push('451 Internal confusion') return # Remove extraneous carriage returns and de-transparency according # to RFC 821, Section 4.5.2. data = [] for text in line.split('\r\n'): if text and text[0] == '.': data.append(text[1:]) else: data.append(text) self.__data = NEWLINE.join(data) status = self.__server.process_message(self.__peer, self.__mailfrom, self.__rcpttos, self.__data) self.__rcpttos = [] self.__mailfrom = None self.__state = self.COMMAND self.set_terminator('\r\n') if not status: self.push('250 Ok') else: self.push(status) server = CustomSMTPServer(('127.0.0.1', 1025), None) asyncore.loop() </code></pre>
2
2009-07-16T15:27:55Z
1,138,474
<p>You need to extend <code>SMTPChannel</code> -- that's where the <code>smtp_</code>verb methods are implemented; your extension of <code>SMTPServer</code> just needs to return your own subclass of the channel.</p>
3
2009-07-16T15:35:15Z
[ "python", "smtp", "smtpd", "smtp-auth" ]
Regex in python
1,138,747
<p>I'm trying to use regular expression right now and I'm really confuse. I want to make some validation with this regular expression : </p> <pre><code>^[A-Za-z0-9_.][A-Za-z0-9_ ]* </code></pre> <p>I want to make it so there is a limit of character (32) and I want to "match" all the string.</p> <p>ex:</p> <p>string : ".hello hello" -this should work</p> <p>string : ".hello hello /.." -This should be rejected because of the /..</p> <p>Thanks!</p>
0
2009-07-16T16:23:43Z
1,138,757
<p>this?</p> <pre><code>^[A-Za-z0-9_.][A-Za-z0-9_ ]{0,31}$ </code></pre>
2
2009-07-16T16:26:15Z
[ "python", "regex", "validation" ]
Regex in python
1,138,747
<p>I'm trying to use regular expression right now and I'm really confuse. I want to make some validation with this regular expression : </p> <pre><code>^[A-Za-z0-9_.][A-Za-z0-9_ ]* </code></pre> <p>I want to make it so there is a limit of character (32) and I want to "match" all the string.</p> <p>ex:</p> <p>string : ".hello hello" -this should work</p> <p>string : ".hello hello /.." -This should be rejected because of the /..</p> <p>Thanks!</p>
0
2009-07-16T16:23:43Z
1,138,765
<p>From 0 to 32 chars: </p> <blockquote> <p>^[\w\d_.]{0,32}$ </p> </blockquote>
0
2009-07-16T16:27:44Z
[ "python", "regex", "validation" ]
Alternative XML parser for ElementTree to ease UTF-8 woes?
1,139,090
<p>I am parsing some XML with the elementtree.parse() function. It works, except for some utf-8 characters(single byte character above 128). I see that the default parser is XMLTreeBuilder which is based on expat.</p> <p>Is there an alternative parser that I can use that may be less strict and allow utf-8 characters?</p> <p>This is the error I'm getting with the default parser:</p> <pre><code>ExpatError: not well-formed (invalid token): line 311, column 190 </code></pre> <p>The character causing this is a single byte x92 (in hex). I'm not certain this is even a valid utf-8 character. But it would be nice to handle it because most text editors display this as: í</p> <p><strong>EDIT</strong>: The context of the character is: canít , where I assume it is supposed to be a fancy apostraphe, but in the hex editor, that same sequence is: 63 61 6E 92 74 </p>
9
2009-07-16T17:32:17Z
1,139,156
<p>Byte 0x92 is never valid as the <em>first byte</em> of a UTF-8 character. It can be valid as a subsequent byte, however. See <a href="http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8" rel="nofollow">this UTF-8 guide</a> for a table of valid byte sequences.</p> <p>Could you give us an idea of what bytes are surrounding 0x92? Does the XML declaration include a character encoding?</p>
1
2009-07-16T17:41:49Z
[ "python", "xml", "utf-8", "elementtree" ]
Alternative XML parser for ElementTree to ease UTF-8 woes?
1,139,090
<p>I am parsing some XML with the elementtree.parse() function. It works, except for some utf-8 characters(single byte character above 128). I see that the default parser is XMLTreeBuilder which is based on expat.</p> <p>Is there an alternative parser that I can use that may be less strict and allow utf-8 characters?</p> <p>This is the error I'm getting with the default parser:</p> <pre><code>ExpatError: not well-formed (invalid token): line 311, column 190 </code></pre> <p>The character causing this is a single byte x92 (in hex). I'm not certain this is even a valid utf-8 character. But it would be nice to handle it because most text editors display this as: í</p> <p><strong>EDIT</strong>: The context of the character is: canít , where I assume it is supposed to be a fancy apostraphe, but in the hex editor, that same sequence is: 63 61 6E 92 74 </p>
9
2009-07-16T17:32:17Z
1,139,556
<p>It looks like you have CP1252 text. If so, it should be specified at the top of the file, eg.:</p> <pre><code>&lt;?xml version="1.0" encoding="CP1252" ?&gt; </code></pre> <p>This does work with ElementTree.</p> <p>If you're creating these files yourself, don't write them in this encoding. Save them as UTF-8 and do your part to help kill obsolete text encodings.</p> <p>If you're receiving CP1252 data with no encoding specification, and you know for sure that it's always going to be CP1252, you can just convert it to UTF-8 before sending it to the parser:</p> <pre><code>s.decode("CP1252").encode("UTF-8") </code></pre>
4
2009-07-16T18:49:48Z
[ "python", "xml", "utf-8", "elementtree" ]
Alternative XML parser for ElementTree to ease UTF-8 woes?
1,139,090
<p>I am parsing some XML with the elementtree.parse() function. It works, except for some utf-8 characters(single byte character above 128). I see that the default parser is XMLTreeBuilder which is based on expat.</p> <p>Is there an alternative parser that I can use that may be less strict and allow utf-8 characters?</p> <p>This is the error I'm getting with the default parser:</p> <pre><code>ExpatError: not well-formed (invalid token): line 311, column 190 </code></pre> <p>The character causing this is a single byte x92 (in hex). I'm not certain this is even a valid utf-8 character. But it would be nice to handle it because most text editors display this as: í</p> <p><strong>EDIT</strong>: The context of the character is: canít , where I assume it is supposed to be a fancy apostraphe, but in the hex editor, that same sequence is: 63 61 6E 92 74 </p>
9
2009-07-16T17:32:17Z
1,139,580
<p>Ah. That is "can´t", obviously, and indeed, 0x92 is an apostrophe in many Windows code pages. Your editor assumes instead that it's a Mac file. ;)</p> <p>If it's a one-off, fixing the file is the right thing to do. But almost always when you need to import other peoples XML there is a lot of things that simply do not agree with the stated encoding. I've found that the best solution is to decode with error setting 'xmlcharrefreplace', and in severe cases do your own custom character replacement that fixes the most common problems for that particular customer.</p> <p>I'll also recommend lxml as XML library in Python, but that's not the problem here.</p>
1
2009-07-16T18:53:36Z
[ "python", "xml", "utf-8", "elementtree" ]
Alternative XML parser for ElementTree to ease UTF-8 woes?
1,139,090
<p>I am parsing some XML with the elementtree.parse() function. It works, except for some utf-8 characters(single byte character above 128). I see that the default parser is XMLTreeBuilder which is based on expat.</p> <p>Is there an alternative parser that I can use that may be less strict and allow utf-8 characters?</p> <p>This is the error I'm getting with the default parser:</p> <pre><code>ExpatError: not well-formed (invalid token): line 311, column 190 </code></pre> <p>The character causing this is a single byte x92 (in hex). I'm not certain this is even a valid utf-8 character. But it would be nice to handle it because most text editors display this as: í</p> <p><strong>EDIT</strong>: The context of the character is: canít , where I assume it is supposed to be a fancy apostraphe, but in the hex editor, that same sequence is: 63 61 6E 92 74 </p>
9
2009-07-16T17:32:17Z
1,141,456
<p>I'll start from the question: "Is there an alternative parser that I can use that may be less strict and allow utf-8 characters?"</p> <p>All XML parsers will accept data encoded in UTF-8. In fact, UTF-8 is the default encoding.</p> <p>An XML document may start with a declaration like this:</p> <pre><code>`&lt;?xml version="1.0" encoding="UTF-8"?&gt;` </code></pre> <p>or like this: <code>&lt;?xml version="1.0"?&gt;</code> or not have a declaration at all ... in each case the parser will decode the document using UTF-8.</p> <p>However your data is NOT encoded in UTF-8 ... it's probably Windows-1252 aka cp1252.</p> <p>If the encoding is not UTF-8, then either the creator should include a declaration (or the recipient can prepend one) or the recipient can transcode the data to UTF-8. The following showcases what works and what doesn't:</p> <pre><code>&gt;&gt;&gt; import xml.etree.ElementTree as ET &gt;&gt;&gt; from StringIO import StringIO as sio &gt;&gt;&gt; raw_text = '&lt;root&gt;can\x92t&lt;/root&gt;' # text encoded in cp1252, no XML declaration &gt;&gt;&gt; t = ET.parse(sio(raw_text)) [tracebacks omitted] xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 9 # parser is expecting UTF-8 &gt;&gt;&gt; t = ET.parse(sio('&lt;?xml version="1.0" encoding="UTF-8"?&gt;' + raw_text)) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 47 # parser is expecting UTF-8 again &gt;&gt;&gt; t = ET.parse(sio('&lt;?xml version="1.0" encoding="cp1252"?&gt;' + raw_text)) &gt;&gt;&gt; t.getroot().text u'can\u2019t' # parser was told to expect cp1252; it works &gt;&gt;&gt; import unicodedata &gt;&gt;&gt; unicodedata.name(u'\u2019') 'RIGHT SINGLE QUOTATION MARK' # not quite an apostrophe, but better than an exception &gt;&gt;&gt; fixed_text = raw_text.decode('cp1252').encode('utf8') # alternative: we transcode the data to UTF-8 &gt;&gt;&gt; t = ET.parse(sio(fixed_text)) &gt;&gt;&gt; t.getroot().text u'can\u2019t' # UTF-8 is the default; no declaration needed </code></pre>
14
2009-07-17T04:43:54Z
[ "python", "xml", "utf-8", "elementtree" ]
Google App engine template unicode decoding problem
1,139,151
<p>When trying to render a Django template file in Google App Engine</p> <blockquote> <p>from google.appengine.ext.webapp import template</p> <p>templatepath = os.path.join(os.path.dirname(<strong>file</strong>), 'template.html')<br> self.response.out.write (template.render( templatepath , template_values))</p> </blockquote> <p>I come across the following error:</p> <blockquote> <p>&lt;type 'exceptions.UnicodeDecodeError'&gt;: 'ascii' codec can't decode byte 0xe2 in position 17692: ordinal not in range(128)<br> args = ('ascii', '&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Str...07/a-beautiful-method-to-find-peace-of-mind/ --&gt;<br> ', 17692, 17693, 'ordinal not in range(128)')<br> encoding = 'ascii'<br> end = 17693<br> message = ''<br> object = '&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Str...07/a-beautiful-method-to-find-peace-of-mind/ --&gt;<br> reason = 'ordinal not in range(128)'<br> start = 17692<br></p> </blockquote> <p>It seems that the underlying django template engine has assumed the "ascii" encoding, which should have been "utf-8". Anyone who knows what might have caused the trouble and how to solve it? Thanks.</p>
2
2009-07-16T17:40:56Z
1,139,534
<p>Did you check in your text editor that the template is encoded in utf-8? </p>
1
2009-07-16T18:46:13Z
[ "python", "django", "google-app-engine", "unicode" ]
Google App engine template unicode decoding problem
1,139,151
<p>When trying to render a Django template file in Google App Engine</p> <blockquote> <p>from google.appengine.ext.webapp import template</p> <p>templatepath = os.path.join(os.path.dirname(<strong>file</strong>), 'template.html')<br> self.response.out.write (template.render( templatepath , template_values))</p> </blockquote> <p>I come across the following error:</p> <blockquote> <p>&lt;type 'exceptions.UnicodeDecodeError'&gt;: 'ascii' codec can't decode byte 0xe2 in position 17692: ordinal not in range(128)<br> args = ('ascii', '&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Str...07/a-beautiful-method-to-find-peace-of-mind/ --&gt;<br> ', 17692, 17693, 'ordinal not in range(128)')<br> encoding = 'ascii'<br> end = 17693<br> message = ''<br> object = '&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Str...07/a-beautiful-method-to-find-peace-of-mind/ --&gt;<br> reason = 'ordinal not in range(128)'<br> start = 17692<br></p> </blockquote> <p>It seems that the underlying django template engine has assumed the "ascii" encoding, which should have been "utf-8". Anyone who knows what might have caused the trouble and how to solve it? Thanks.</p>
2
2009-07-16T17:40:56Z
1,140,751
<p>Are you using Django 0.96 or Django 1.0? You can check by looking at your main.py and seeing if it contains the following: </p> <pre> from google.appengine.dist import use_library use_library('django', '1.0')</pre> <p>If you're using Django 1.0, both FILE_CHARSET and DEFAULT_CHARSET should default to 'utf-8'. If your template is saved under a different encoding, just set FILE_CHARSET to whatever that is.</p> <p>If you're using Django 0.96, you might want to try directly reading the template from the disk and then manually handling the encoding.</p> <p>e.g., replace </p> <p><code>template.render( templatepath , template_values)</code> </p> <p>with </p> <p><code>Template(unicode(template_fh.read(), 'utf-8')).render(template_values)</code></p>
2
2009-07-16T23:02:34Z
[ "python", "django", "google-app-engine", "unicode" ]
Google App engine template unicode decoding problem
1,139,151
<p>When trying to render a Django template file in Google App Engine</p> <blockquote> <p>from google.appengine.ext.webapp import template</p> <p>templatepath = os.path.join(os.path.dirname(<strong>file</strong>), 'template.html')<br> self.response.out.write (template.render( templatepath , template_values))</p> </blockquote> <p>I come across the following error:</p> <blockquote> <p>&lt;type 'exceptions.UnicodeDecodeError'&gt;: 'ascii' codec can't decode byte 0xe2 in position 17692: ordinal not in range(128)<br> args = ('ascii', '&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Str...07/a-beautiful-method-to-find-peace-of-mind/ --&gt;<br> ', 17692, 17693, 'ordinal not in range(128)')<br> encoding = 'ascii'<br> end = 17693<br> message = ''<br> object = '&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Str...07/a-beautiful-method-to-find-peace-of-mind/ --&gt;<br> reason = 'ordinal not in range(128)'<br> start = 17692<br></p> </blockquote> <p>It seems that the underlying django template engine has assumed the "ascii" encoding, which should have been "utf-8". Anyone who knows what might have caused the trouble and how to solve it? Thanks.</p>
2
2009-07-16T17:40:56Z
1,141,420
<p>Well, turns out the rendered results returned by the template needs to be decoded first:</p> <blockquote> <p>self.response.out.write (template.render( templatepath , template_values).decode('utf-8') )</p> </blockquote> <p>A silly mistake, but thanks for everyone's answers anyway. :)</p>
6
2009-07-17T04:21:06Z
[ "python", "django", "google-app-engine", "unicode" ]
Python RSA Decryption Using OpenSSL Generated Keys
1,139,622
<p>Does anyone know the simplest way to import an OpenSSL RSA private/public key (using a passphrase) with a Python library and use it to decrypt a message.</p> <p>I've taken a look at ezPyCrypto, but can't seem to get it to recognise an OpenSSL RSA key, I've tried importing a key with importKey as follows:</p> <pre><code>key.importKey(myKey, passphrase='PASSPHRASE') </code></pre> <p>myKey in my case is an OpenSSL RSA public/private keypair represented as a string. </p> <p>This balks with:</p> <blockquote> <p>unbound method importKey() must be called with key instance as first argument (got str instance instead)</p> </blockquote> <p>The API doc says:</p> <blockquote> <p>importKey(self, keystring, **kwds)</p> </blockquote> <p>Can somebody suggest how I read a key in using ezPyCrypto? I've also tried:</p> <pre><code>key(key, passphrase='PASSPHRASE') </code></pre> <p>but this balks with:</p> <blockquote> <p>ezPyCrypto.CryptoKeyError: Attempted to import invalid key, or passphrase is bad</p> </blockquote> <p>Link to docs here:</p> <p><a href="http://www.freenet.org.nz/ezPyCrypto/detail/index.html" rel="nofollow">http://www.freenet.org.nz/ezPyCrypto/detail/index.html</a></p> <p><strong>EDIT:</strong> Just an update on this. Successfully imported an RSA key, but had real problem decrypting because eqPyCrypto doesn't support the AES block cipher. Just so that people know. I successfully managed to do what I wanted using ncrypt (<a href="http://tachyon.in/ncrypt/" rel="nofollow">http://tachyon.in/ncrypt/</a>). I had some compilation issues with M2Crypto because of SWIG and OpenSSL compilation problems, <em>despite</em> having versions installed that exceeded the minimum requirements. It would seem that the Python encryption/decryption frameworks are a bit of a minefield at the moment. Ho hum, thanks for your help.</p>
4
2009-07-16T19:00:44Z
1,139,731
<p>The first error is telling you that <code>importKey</code> needs to be called on an <em>instance</em> of <code>key</code>.</p> <pre><code>k = key() k.importKey(myKey, passphrase='PASSPHRASE') </code></pre> <p>However, the documentation seems to suggest that this is a better way of doing what you want:</p> <pre><code>k = key(keyobj=myKey, passphrase='PASSPHRASE') </code></pre>
6
2009-07-16T19:18:07Z
[ "python", "openssl", "rsa", "encryption" ]
Python RSA Decryption Using OpenSSL Generated Keys
1,139,622
<p>Does anyone know the simplest way to import an OpenSSL RSA private/public key (using a passphrase) with a Python library and use it to decrypt a message.</p> <p>I've taken a look at ezPyCrypto, but can't seem to get it to recognise an OpenSSL RSA key, I've tried importing a key with importKey as follows:</p> <pre><code>key.importKey(myKey, passphrase='PASSPHRASE') </code></pre> <p>myKey in my case is an OpenSSL RSA public/private keypair represented as a string. </p> <p>This balks with:</p> <blockquote> <p>unbound method importKey() must be called with key instance as first argument (got str instance instead)</p> </blockquote> <p>The API doc says:</p> <blockquote> <p>importKey(self, keystring, **kwds)</p> </blockquote> <p>Can somebody suggest how I read a key in using ezPyCrypto? I've also tried:</p> <pre><code>key(key, passphrase='PASSPHRASE') </code></pre> <p>but this balks with:</p> <blockquote> <p>ezPyCrypto.CryptoKeyError: Attempted to import invalid key, or passphrase is bad</p> </blockquote> <p>Link to docs here:</p> <p><a href="http://www.freenet.org.nz/ezPyCrypto/detail/index.html" rel="nofollow">http://www.freenet.org.nz/ezPyCrypto/detail/index.html</a></p> <p><strong>EDIT:</strong> Just an update on this. Successfully imported an RSA key, but had real problem decrypting because eqPyCrypto doesn't support the AES block cipher. Just so that people know. I successfully managed to do what I wanted using ncrypt (<a href="http://tachyon.in/ncrypt/" rel="nofollow">http://tachyon.in/ncrypt/</a>). I had some compilation issues with M2Crypto because of SWIG and OpenSSL compilation problems, <em>despite</em> having versions installed that exceeded the minimum requirements. It would seem that the Python encryption/decryption frameworks are a bit of a minefield at the moment. Ho hum, thanks for your help.</p>
4
2009-07-16T19:00:44Z
1,139,800
<p>It is not clear what are you trying to achieve, but you could give M2Crypto a try. From my point of view it is the best OpenSSL wrapper available for Python.</p> <p>Here is a sample RSA encryption/decription code:</p> <pre><code>import M2Crypto as m2c import textwrap key = m2c.RSA.load_key('key.pem', lambda prompt: 'mypassword') # encrypt something: data = 'testing 123' encrypted = key.public_encrypt(data, m2c.RSA.pkcs1_padding) print "Encrypted data:" print "\n".join(textwrap.wrap(' '.join(['%02x' % ord(b) for b in encrypted ]))) # and now decrypt it: decrypted = key.private_decrypt(encrypted, m2c.RSA.pkcs1_padding) print "Decrypted data:" print decrypted print data == decrypted </code></pre>
5
2009-07-16T19:33:14Z
[ "python", "openssl", "rsa", "encryption" ]
Python inheritance and calling parent class constructor
1,139,828
<p>This is what I'm trying to do in Python: </p> <pre><code>class BaseClass: def __init__(self): print 'The base class constructor ran!' self.__test = 42 class ChildClass(BaseClass): def __init__(self): print 'The child class constructor ran!' BaseClass.__init__(self) def doSomething(self): print 'Test is: ', self.__test test = ChildClass() test.doSomething() </code></pre> <p>Which results in: </p> <pre><code>AttributeError: ChildClass instance has no attribute '_ChildClass__test' </code></pre> <p>What gives? Why doesn't this work as I expect?</p>
14
2009-07-16T19:37:13Z
1,139,845
<p>From python documentation:</p> <blockquote> <p>Private name mangling: When an identifier that textually occurs in a class definition <strong>begins with two or more underscore</strong> characters and does not end in two or more underscores, it is considered a <strong>private name</strong> of that class. Private names are <strong>transformed to a longer form</strong> before code is generated for them. The transformation <strong>inserts the class name in front of the name</strong>, with leading underscores removed, and a single underscore inserted in front of the class name. For example, the identifier <strong>__spam</strong> occurring in a class named <strong>Ham</strong> will be transformed to <strong>_Ham__spam</strong>. This transformation is independent of the syntactical context in which the identifier is used. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done.</p> </blockquote> <p>So your attribute is not named <strong>__test</strong> but <strong>_BaseClass__test</strong>.</p> <p>However you should not depend on that, use <strong>self._test</strong> instead and most python developers will know that the attribute is an internal part of the class, not the public interface. </p>
20
2009-07-16T19:39:04Z
[ "python", "oop" ]
Python inheritance and calling parent class constructor
1,139,828
<p>This is what I'm trying to do in Python: </p> <pre><code>class BaseClass: def __init__(self): print 'The base class constructor ran!' self.__test = 42 class ChildClass(BaseClass): def __init__(self): print 'The child class constructor ran!' BaseClass.__init__(self) def doSomething(self): print 'Test is: ', self.__test test = ChildClass() test.doSomething() </code></pre> <p>Which results in: </p> <pre><code>AttributeError: ChildClass instance has no attribute '_ChildClass__test' </code></pre> <p>What gives? Why doesn't this work as I expect?</p>
14
2009-07-16T19:37:13Z
1,139,850
<p>Double underscored variables can be considered "private". They are mangled with the class name, amongst other to protect multiple baseclasses from overriding eachothers members.</p> <p>Use a single underscore if you want your attribute to be considered private by other developers.</p>
3
2009-07-16T19:41:17Z
[ "python", "oop" ]
Python inheritance and calling parent class constructor
1,139,828
<p>This is what I'm trying to do in Python: </p> <pre><code>class BaseClass: def __init__(self): print 'The base class constructor ran!' self.__test = 42 class ChildClass(BaseClass): def __init__(self): print 'The child class constructor ran!' BaseClass.__init__(self) def doSomething(self): print 'Test is: ', self.__test test = ChildClass() test.doSomething() </code></pre> <p>Which results in: </p> <pre><code>AttributeError: ChildClass instance has no attribute '_ChildClass__test' </code></pre> <p>What gives? Why doesn't this work as I expect?</p>
14
2009-07-16T19:37:13Z
1,139,970
<p>You could use Python's introspection facilities to get you the information you are looking for. A simple dir(test) will give you</p> <pre><code>['_BaseClass__test', '__doc__', '__init__', '__module__', 'doSomething'] </code></pre> <p>Note the '_BaseClass__test'. That's what you're looking for.</p> <p>Check <a href="http://docs.python.org/tutorial/classes.html">this</a> for more information.</p>
5
2009-07-16T20:06:41Z
[ "python", "oop" ]
Python fails to execute firefox webbrowser from a root executed script with privileges drop
1,139,835
<p>I can't run firefox from a sudoed python script that drops privileges to normal user. If i write</p> <pre> $ sudo python >>> import os >>> import pwd, grp >>> uid = pwd.getpwnam('norby')[2] >>> gid = grp.getgrnam('norby')[2] >>> os.setegid(gid) >>> os.seteuid(uid) >>> import webbrowser >>> webbrowser.get('firefox').open('www.google.it') True >>> # It returns true but doesn't work >>> from subprocess import Popen,PIPE >>> p = Popen('firefox www.google.it', shell=True,stdout=PIPE,stderr=PIPE) >>> # Doesn't execute the command >>> You shouldn't really run Iceweasel through sudo WITHOUT the -H option. Continuing as if you used the -H option. No protocol specified Error: cannot open display: :0 </pre> <p>I think that is not a python problem, but firefox/iceweasel/debian configuration problem. Maybe firefox read only UID and not EUID, and doesn't execute process because UID is equal 0. What do you think about?</p>
0
2009-07-16T19:38:18Z
1,140,199
<p>This could be your environment. Changing the permissions will still leave environment variables like $HOME pointing at the root user's directory, which will be inaccessible. It may be worth trying altering these variables by changing <code>os.environ</code> before launching the browser. There may also be other variables worth checking.</p>
1
2009-07-16T20:47:04Z
[ "python", "browser", "debian", "uid" ]
In Python, how do I obtain the current frame?
1,140,194
<p>In other languages I can obtain the current frame via a reflection api to determine what variables are local to the scope that I an currently in.</p> <p>Is there a way to do this in Python?</p>
20
2009-07-16T20:45:55Z
1,140,211
<p>See the <a href="http://docs.python.org/library/functions.html" rel="nofollow">dir</a> function.</p> <p>sorry - not actually relevant to the frame, but still useful!</p>
-3
2009-07-16T20:48:51Z
[ "python" ]
In Python, how do I obtain the current frame?
1,140,194
<p>In other languages I can obtain the current frame via a reflection api to determine what variables are local to the scope that I an currently in.</p> <p>Is there a way to do this in Python?</p>
20
2009-07-16T20:45:55Z
1,140,231
<pre><code>import sys sys._getframe(number) </code></pre> <p>The number being 0 for the current frame and 1 for the frame up and so on up.</p> <p>The best introduction I have found to frames in python is <a href="http://farmdev.com/src/secrets/framehack/index.html">here</a></p> <p>However, look at the inspect module as it does most common things you want to do with frames.</p>
28
2009-07-16T20:52:27Z
[ "python" ]
In Python, how do I obtain the current frame?
1,140,194
<p>In other languages I can obtain the current frame via a reflection api to determine what variables are local to the scope that I an currently in.</p> <p>Is there a way to do this in Python?</p>
20
2009-07-16T20:45:55Z
1,140,513
<p>I use these little guys for debugging and logging:</p> <pre><code>import sys def LINE( back = 0 ): return sys._getframe( back + 1 ).f_lineno def FILE( back = 0 ): return sys._getframe( back + 1 ).f_code.co_filename def FUNC( back = 0): return sys._getframe( back + 1 ).f_code.co_name def WHERE( back = 0 ): frame = sys._getframe( back + 1 ) return "%s/%s %s()" % ( os.path.basename( frame.f_code.co_filename ), frame.f_lineno, frame.f_code.co_name ) </code></pre>
17
2009-07-16T21:46:50Z
[ "python" ]
In Python, how do I obtain the current frame?
1,140,194
<p>In other languages I can obtain the current frame via a reflection api to determine what variables are local to the scope that I an currently in.</p> <p>Is there a way to do this in Python?</p>
20
2009-07-16T20:45:55Z
16,502,277
<p>The best answer would be to use the <a href="http://docs.python.org/2/library/inspect.html#inspect.currentframe">inspect</a> module; not a private function in <code>sys</code>.</p> <pre><code>import inspect current_frame = inspect.currentframe() </code></pre>
16
2013-05-11T22:23:43Z
[ "python" ]
Using Python to Automate Creation/Manipulation of Excel Spreadsheets
1,140,311
<p>I have some data in CSV format that I want to pull into an Excel spreadsheet and then create some standard set of graphs for. Since the data is originally generated in a Python app, I was hoping to simply extend the app so that it could do all the post processing and I wouldn't have to do it by hand. Is there an easy interface with Python to work with and manipulate Excel spreadsheets? Any good samples of doing this? Is this Windows only (I'm primarily working on a Mac and have Excel, but could do this on Windows if necessary).</p>
3
2009-07-16T20:51:51Z
1,140,366
<p>On Windows you could use the <a href="https://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a> package to create an Excel COM Object and then manipulate it from a script. You need to have an installed Excel on that machine though. I haven't done this myself so I can't give you and details but I've seen this working so can at least confirm that it's possible. No idea about OS X, unfortunately.</p>
1
2009-07-16T21:19:21Z
[ "python", "excel" ]
Using Python to Automate Creation/Manipulation of Excel Spreadsheets
1,140,311
<p>I have some data in CSV format that I want to pull into an Excel spreadsheet and then create some standard set of graphs for. Since the data is originally generated in a Python app, I was hoping to simply extend the app so that it could do all the post processing and I wouldn't have to do it by hand. Is there an easy interface with Python to work with and manipulate Excel spreadsheets? Any good samples of doing this? Is this Windows only (I'm primarily working on a Mac and have Excel, but could do this on Windows if necessary).</p>
3
2009-07-16T20:51:51Z
1,140,370
<p><a href="http://pypi.python.org/pypi/xlutils" rel="nofollow">xlutils</a> (and the included packages <code>xlrd</code> and <code>xlwt</code>) should allow your Python program to handily do any creation, reading and manipulation of Excel files you might want!</p>
7
2009-07-16T21:19:42Z
[ "python", "excel" ]
What’s the best way to get an HTTP response code from a URL?
1,140,661
<p>I’m looking for a quick way to get an HTTP response code from a URL (i.e. 200, 404, etc). I’m not sure which library to use.</p>
38
2009-07-16T22:27:54Z
1,140,675
<p>You should use urllib2, like this:</p> <pre><code>import urllib2 for url in ["http://entrian.com/", "http://entrian.com/does-not-exist/"]: try: connection = urllib2.urlopen(url) print connection.getcode() connection.close() except urllib2.HTTPError, e: print e.getcode() # Prints: # 200 [from the try block] # 404 [from the except block] </code></pre>
19
2009-07-16T22:31:33Z
[ "python" ]
What’s the best way to get an HTTP response code from a URL?
1,140,661
<p>I’m looking for a quick way to get an HTTP response code from a URL (i.e. 200, 404, etc). I’m not sure which library to use.</p>
38
2009-07-16T22:27:54Z
1,140,822
<p>Here's a solution that uses <code>httplib</code> instead.</p> <pre><code>import httplib def get_status_code(host, path="/"): """ This function retreives the status code of a website by requesting HEAD data from the host. This means that it only requests the headers. If the host cannot be reached or something else goes wrong, it returns None instead. """ try: conn = httplib.HTTPConnection(host) conn.request("HEAD", path) return conn.getresponse().status except StandardError: return None print get_status_code("stackoverflow.com") # prints 200 print get_status_code("stackoverflow.com", "/nonexistant") # prints 404 </code></pre>
55
2009-07-16T23:30:43Z
[ "python" ]
What’s the best way to get an HTTP response code from a URL?
1,140,661
<p>I’m looking for a quick way to get an HTTP response code from a URL (i.e. 200, 404, etc). I’m not sure which library to use.</p>
38
2009-07-16T22:27:54Z
1,491,225
<p>The <code>urllib2.HTTPError</code> exception does not contain a <code>getcode()</code> method. Use the <code>code</code> attribute instead.</p>
2
2009-09-29T08:19:50Z
[ "python" ]
What’s the best way to get an HTTP response code from a URL?
1,140,661
<p>I’m looking for a quick way to get an HTTP response code from a URL (i.e. 200, 404, etc). I’m not sure which library to use.</p>
38
2009-07-16T22:27:54Z
12,866,650
<p>In future, for those that use python3 and later, here's another code to find response code.</p> <pre><code>import urllib.request def getResponseCode(url): conn = urllib.request.urlopen(url) return conn.getcode() </code></pre>
2
2012-10-12T20:30:29Z
[ "python" ]
What’s the best way to get an HTTP response code from a URL?
1,140,661
<p>I’m looking for a quick way to get an HTTP response code from a URL (i.e. 200, 404, etc). I’m not sure which library to use.</p>
38
2009-07-16T22:27:54Z
13,641,613
<p>Update using the wonderful <a href="http://docs.python-requests.org/en/latest/">requests library</a>. Note we are using the HEAD request, which should happen more quickly then a full GET or POST request. </p> <pre><code>import requests try: r = requests.head("http://stackoverflow.com") print(r.status_code) # prints the int of the status code. Find more at httpstatusrappers.com :) except requests.ConnectionError: print("failed to connect") </code></pre>
40
2012-11-30T08:40:39Z
[ "python" ]
What’s the best way to get an HTTP response code from a URL?
1,140,661
<p>I’m looking for a quick way to get an HTTP response code from a URL (i.e. 200, 404, etc). I’m not sure which library to use.</p>
38
2009-07-16T22:27:54Z
22,123,762
<p>Here's an <code>httplib</code> solution that behaves like urllib2. You can just give it a URL and it just works. No need to mess about splitting up your URLs into hostname and path. This function already does that.</p> <pre><code>import httplib import socket def get_link_status(url): """ Gets the HTTP status of the url or returns an error associated with it. Always returns a string. """ https=False url=re.sub(r'(.*)#.*$',r'\1',url) url=url.split('/',3) if len(url) &gt; 3: path='/'+url[3] else: path='/' if url[0] == 'http:': port=80 elif url[0] == 'https:': port=443 https=True if ':' in url[2]: host=url[2].split(':')[0] port=url[2].split(':')[1] else: host=url[2] try: headers={'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0', 'Host':host } if https: conn=httplib.HTTPSConnection(host=host,port=port,timeout=10) else: conn=httplib.HTTPConnection(host=host,port=port,timeout=10) conn.request(method="HEAD",url=path,headers=headers) response=str(conn.getresponse().status) conn.close() except socket.gaierror,e: response="Socket Error (%d): %s" % (e[0],e[1]) except StandardError,e: if hasattr(e,'getcode') and len(e.getcode()) &gt; 0: response=str(e.getcode()) if hasattr(e, 'message') and len(e.message) &gt; 0: response=str(e.message) elif hasattr(e, 'msg') and len(e.msg) &gt; 0: response=str(e.msg) elif type('') == type(e): response=e else: response="Exception occurred without a good error message. Manually check the URL to see the status. If it is believed this URL is 100% good then file a issue for a potential bug." return response </code></pre>
-1
2014-03-02T04:14:55Z
[ "python" ]
Add local variable to running generator
1,140,665
<p>Lately, I tried to set local variables from outside of a running generator. The generator code also should access these variables.</p> <p>One trouble was, that when accessing the variables, it seamed that the interpreter was thinking it must be a global since the variable was not set in the local scope. But I don't wanted to change the global variables and did also not want to copy the whole global scope to make the variables artificially local.</p> <p>An other trouble was, that it seams that the dictionaries for locals (and globals?) seamed to be read-only when accessed from outside.</p> <p>Is there any legal (or at least partial legal way) to introduce locals into a running generator instance?</p> <p>Edit for clarification:</p> <p>I don't mean the "send" function. This is of course a neat function, but since I want to set multiple variables with differing names, it is not conveniant for my purposes.</p>
1
2009-07-16T22:28:34Z
1,140,700
<p>locals() always returns a read-only dict. You could create your own "locals" dictionary:</p> <pre><code>def gen_func(): lcls = {} for i in range(5): yield (i, lcls) print lcls for (val, lcls) in gen_func(): lcls[val] = val </code></pre> <p>Any other mutable structure will also work.</p>
0
2009-07-16T22:38:18Z
[ "python", "variables", "generator", "local" ]
Add local variable to running generator
1,140,665
<p>Lately, I tried to set local variables from outside of a running generator. The generator code also should access these variables.</p> <p>One trouble was, that when accessing the variables, it seamed that the interpreter was thinking it must be a global since the variable was not set in the local scope. But I don't wanted to change the global variables and did also not want to copy the whole global scope to make the variables artificially local.</p> <p>An other trouble was, that it seams that the dictionaries for locals (and globals?) seamed to be read-only when accessed from outside.</p> <p>Is there any legal (or at least partial legal way) to introduce locals into a running generator instance?</p> <p>Edit for clarification:</p> <p>I don't mean the "send" function. This is of course a neat function, but since I want to set multiple variables with differing names, it is not conveniant for my purposes.</p>
1
2009-07-16T22:28:34Z
1,140,735
<p>What you may be looking for, is the <a href="http://docs.python.org/reference/expressions.html#generator.send" rel="nofollow"><code>send</code></a> method, which allows a value to be <em>sent into</em> a generator. <a href="http://docs.python.org/reference/expressions.html#yield-expressions" rel="nofollow">The reference</a> provides an example:</p> <pre><code>&gt;&gt;&gt; def echo(value=None): ... print "Execution starts when 'next()' is called for the first time." ... try: ... while True: ... try: ... value = (yield value) ... except Exception, e: ... value = e ... finally: ... print "Don't forget to clean up when 'close()' is called." ... &gt;&gt;&gt; generator = echo(1) &gt;&gt;&gt; print generator.next() Execution starts when 'next()' is called for the first time. 1 &gt;&gt;&gt; print generator.next() None &gt;&gt;&gt; print generator.send(2) 2 &gt;&gt;&gt; generator.throw(TypeError, "spam") TypeError('spam',) &gt;&gt;&gt; generator.close() Don't forget to clean up when 'close()' is called. </code></pre> <p><hr /></p> <p>Let me give an example of my own. <strong>(Watch out! The code above is Python 2.6, but below I'll write Python 3; <a href="http://docs.python.org/3.0/reference/expressions.html#yield-expressions" rel="nofollow">py3k ref</a>)</strong>:</p> <pre><code>&gt;&gt;&gt; def amplify(iter, amp=1): ... for i in iter: ... reply = (yield i * amp) ... amp = reply if reply != None else amp ... &gt;&gt;&gt; it = amplify(range(10)) &gt;&gt;&gt; next(it) 0 &gt;&gt;&gt; next(it) 1 &gt;&gt;&gt; it.send(3) # 2 * 3 = 6 6 &gt;&gt;&gt; it.send(8) # 3 * 8 = 24 24 &gt;&gt;&gt; next(it) # 4 * 8 = 32 32 </code></pre> <p>Of course, if your really want to, you can also do this without <code>send</code>. E.g. by encapsulating the generator inside a class (but it's not nearly as elegant!):</p> <pre><code>&gt;&gt;&gt; class MyIter: ... def __init__(self, iter, amp=1): ... self.iter = iter ... self.amp = amp ... def __iter__(self): ... for i in self.iter: ... yield i * self.amp ... def __call__(self): ... return iter(self) ... &gt;&gt;&gt; iterable = MyIter(range(10)) &gt;&gt;&gt; iterator = iterable() &gt;&gt;&gt; next(iterator) 0 &gt;&gt;&gt; next(iterator) 1 &gt;&gt;&gt; iterable.amp = 3 &gt;&gt;&gt; next(iterator) 6 &gt;&gt;&gt; iterable.amp = 8 &gt;&gt;&gt; next(iterator) 24 &gt;&gt;&gt; next(iterator) 32 </code></pre> <p><hr /></p> <p><strong>Update:</strong> Alright, now that you have updated your question, let me have another stab at the problem. Perhaps this is what you mean?</p> <pre><code>&gt;&gt;&gt; def amplify(iter, loc={}): ... for i in iter: ... yield i * loc.get('amp', 1) ... &gt;&gt;&gt; it = amplify(range(10), locals()) &gt;&gt;&gt; next(it) 0 &gt;&gt;&gt; next(it) 1 &gt;&gt;&gt; amp = 3 &gt;&gt;&gt; next(it) 6 &gt;&gt;&gt; amp = 8 &gt;&gt;&gt; next(it) 24 &gt;&gt;&gt; next(it) 32 </code></pre> <p>Note that <a href="http://docs.python.org/3.0/library/functions.html#locals" rel="nofollow"><code>locals()</code></a> should be treated as read-only and is scope dependent. As you can see, you'll need to explicitly pass <code>locals()</code> to the generator. I see no way around this...</p>
4
2009-07-16T22:56:04Z
[ "python", "variables", "generator", "local" ]
Add local variable to running generator
1,140,665
<p>Lately, I tried to set local variables from outside of a running generator. The generator code also should access these variables.</p> <p>One trouble was, that when accessing the variables, it seamed that the interpreter was thinking it must be a global since the variable was not set in the local scope. But I don't wanted to change the global variables and did also not want to copy the whole global scope to make the variables artificially local.</p> <p>An other trouble was, that it seams that the dictionaries for locals (and globals?) seamed to be read-only when accessed from outside.</p> <p>Is there any legal (or at least partial legal way) to introduce locals into a running generator instance?</p> <p>Edit for clarification:</p> <p>I don't mean the "send" function. This is of course a neat function, but since I want to set multiple variables with differing names, it is not conveniant for my purposes.</p>
1
2009-07-16T22:28:34Z
1,140,891
<p>If you want to have a coroutine or a generator that also acts as a sink, you should use the send method, as in <a href="http://stackoverflow.com/questions/1140665/add-local-variable-to-running-generator/1140735#1140735">Stephan202's answers</a>. If you want to change the runtime behavior by settings various attributes in the generator, there's an old <a href="http://code.activestate.com/recipes/164044/" rel="nofollow">recipe</a> by Raymond Hettinger:</p> <pre><code>def foo_iter(self): self.v = "foo" while True: yield self.v enableAttributes(foo_iter) it = foo_iter() print it.next() it.v = "boo" print it.next() </code></pre> <p>This will print:</p> <pre><code>foo boo </code></pre> <p>It shouldn't be too difficult to convert the <code>enableAttributes</code> function into a proper decorator. </p>
1
2009-07-16T23:59:36Z
[ "python", "variables", "generator", "local" ]
xml.parsers.expat.ExpatError on parsing XML
1,140,672
<p>I am trying to parse XML with Python but not getting very far. I think it's due to wrong XML tree this API returns.</p> <p>So this is what is returned by the GET request:</p> <pre><code>&lt;codigo&gt;3&lt;/codigo&gt;&lt;valor&gt;&lt;/valor&gt;&lt;operador&gt;Dummy&lt;/operador&gt; </code></pre> <p>The GET request goes here:</p> <pre><code>http://69.36.9.147:8090/clientes/SMS_API_OUT.jsp?codigo=ABCDEFGH&amp;cliente=XX </code></pre> <p>This is the Python code I am using without any luck:</p> <pre><code>import urllib from xml.dom import minidom url = urllib.urlopen('http://69.36.9.147:8090/clientes/SMS_API_OUT.jsp?codigo=ABCDEFGH&amp;cliente=XX') xml = minidom.parse(url) code = doc.getElementsByTagName('codigo') print code[0].data </code></pre> <p>And this is the response I get:</p> <pre><code>xml.parsers.expat.ExpatError: junk after document element: line 1, column 18 </code></pre> <p>What I need to do is retrieve the value inside the <code>&lt;codigo&gt;</code> element and place it in a variable (same for the others).</p>
6
2009-07-16T22:30:28Z
1,140,708
<p>An XML document consists of <em>one</em> top level document element, and then multiple subelements. Your XML fragment contains multiple top level elements, which is not permitted by the XML standard.</p> <p>Try returning something like:</p> <pre><code>&lt;result&gt;&lt;codigo&gt;3&lt;/codigo&gt;&lt;valor&gt;&lt;/valor&gt;&lt;operador&gt;Dummy&lt;/operador&gt;&lt;/result&gt; </code></pre> <p>I have wrapped the entire response in a <code>&lt;result&gt;</code> tag.</p>
2
2009-07-16T22:40:22Z
[ "python", "xml" ]
xml.parsers.expat.ExpatError on parsing XML
1,140,672
<p>I am trying to parse XML with Python but not getting very far. I think it's due to wrong XML tree this API returns.</p> <p>So this is what is returned by the GET request:</p> <pre><code>&lt;codigo&gt;3&lt;/codigo&gt;&lt;valor&gt;&lt;/valor&gt;&lt;operador&gt;Dummy&lt;/operador&gt; </code></pre> <p>The GET request goes here:</p> <pre><code>http://69.36.9.147:8090/clientes/SMS_API_OUT.jsp?codigo=ABCDEFGH&amp;cliente=XX </code></pre> <p>This is the Python code I am using without any luck:</p> <pre><code>import urllib from xml.dom import minidom url = urllib.urlopen('http://69.36.9.147:8090/clientes/SMS_API_OUT.jsp?codigo=ABCDEFGH&amp;cliente=XX') xml = minidom.parse(url) code = doc.getElementsByTagName('codigo') print code[0].data </code></pre> <p>And this is the response I get:</p> <pre><code>xml.parsers.expat.ExpatError: junk after document element: line 1, column 18 </code></pre> <p>What I need to do is retrieve the value inside the <code>&lt;codigo&gt;</code> element and place it in a variable (same for the others).</p>
6
2009-07-16T22:30:28Z
1,140,753
<p>The main problem here is that the XML code being returned by that service doesn't include a root node, which is invalid. I fixed this by simply wrapping the output in a <code>&lt;root&gt;</code> node.</p> <pre><code>import urllib from xml.etree import ElementTree url = 'http://69.36.9.147:8090/clientes/SMS_API_OUT.jsp?codigo=ABCDEFGH&amp;cliente=XX' xmldata = '&lt;root&gt;' + urllib.urlopen(url).read() + '&lt;/root&gt;' tree = ElementTree.fromstring(xmldata) codigo = tree.find('codigo').text print codigo </code></pre> <p>You can use whatever parser you wish, but here I used ElementTree to get the value.</p>
12
2009-07-16T23:03:34Z
[ "python", "xml" ]
How can I get the string result of a python method from the XML-RPC client in Java
1,140,752
<p>I wrote:</p> <pre><code>Object result = (Object)client.execute("method",params); </code></pre> <p>in java client.</p> <p>Actually, the result should be printed in string format. But I can only output the address of "Object result", how can I get the content?</p> <p>And I have tried String result = (String)client.execute("method",params);</p> <p>It says lang.until.Object can not cast to lang.util.String.</p> <p>As the server is written in Python, I was wondering how can I retrieve String from the method.</p>
0
2009-07-16T23:03:19Z
1,140,895
<p>I'm hesitant to post this because it seems rather obvious - forgive me if you've tried this, but how about:</p> <pre><code>String result = (String)client.execute("method",params); </code></pre>
0
2009-07-16T23:59:54Z
[ "java", "python", "xml-rpc" ]
How can I get the string result of a python method from the XML-RPC client in Java
1,140,752
<p>I wrote:</p> <pre><code>Object result = (Object)client.execute("method",params); </code></pre> <p>in java client.</p> <p>Actually, the result should be printed in string format. But I can only output the address of "Object result", how can I get the content?</p> <p>And I have tried String result = (String)client.execute("method",params);</p> <p>It says lang.until.Object can not cast to lang.util.String.</p> <p>As the server is written in Python, I was wondering how can I retrieve String from the method.</p>
0
2009-07-16T23:03:19Z
1,141,346
<p>so maybe the object returned is not a string... are you sure that you're returning a string in your python application? I seriously doubt it.</p>
0
2009-07-17T03:37:59Z
[ "java", "python", "xml-rpc" ]
Parsing Meaning from Text
1,140,908
<p>I realize this is a broad topic, but I'm looking for a good primer on parsing meaning from text, ideally in Python. As an example of what I'm looking to do, if a user makes a blog post like:</p> <p>"Manny Ramirez makes his return for the Dodgers today against the Houston Astros",</p> <p>what's a light-weight/ easy way of getting the nouns out of a sentence? To start, I think I'd limit it to proper nouns, but I wouldn't want to be limited to just that (and I don't want to rely on a simple regex that assumes anything Title Capped is a proper noun).</p> <p>To make this question even worse, what are the things I'm not asking that I should be? Do I need a corpus of existing words to get started? What lexical analysis stuff do I need to know to make this work? I did come across <a href="http://stackoverflow.com/questions/220187/algorithms-or-libraries-for-textual-analysis-specifically-dominant-words-phras">one other question</a> on the topic and I'm digging through those resources now.</p>
9
2009-07-17T00:05:09Z
1,140,917
<p>You need to look at the <a href="http://www.nltk.org/">Natural Language Toolkit</a>, which is for exactly this sort of thing.</p> <p>This section of the manual looks very relevant: <a href="http://nltk.googlecode.com/svn/trunk/doc/book/ch05.html">Categorizing and Tagging Words</a> - here's an extract:</p> <pre><code>&gt;&gt;&gt; text = nltk.word_tokenize("And now for something completely different") &gt;&gt;&gt; nltk.pos_tag(text) [('And', 'CC'), ('now', 'RB'), ('for', 'IN'), ('something', 'NN'), ('completely', 'RB'), ('different', 'JJ')] </code></pre> <p><em>Here we see that <strong>and</strong> is CC, a coordinating conjunction; <strong>now</strong> and <strong>completely</strong> are RB, or adverbs; <strong>for</strong> is IN, a preposition; <strong>something</strong> is NN, a noun; and <strong>different</strong> is JJ, an adjective.</em></p>
8
2009-07-17T00:07:54Z
[ "python", "parsing", "nlp", "lexical-analysis" ]
Parsing Meaning from Text
1,140,908
<p>I realize this is a broad topic, but I'm looking for a good primer on parsing meaning from text, ideally in Python. As an example of what I'm looking to do, if a user makes a blog post like:</p> <p>"Manny Ramirez makes his return for the Dodgers today against the Houston Astros",</p> <p>what's a light-weight/ easy way of getting the nouns out of a sentence? To start, I think I'd limit it to proper nouns, but I wouldn't want to be limited to just that (and I don't want to rely on a simple regex that assumes anything Title Capped is a proper noun).</p> <p>To make this question even worse, what are the things I'm not asking that I should be? Do I need a corpus of existing words to get started? What lexical analysis stuff do I need to know to make this work? I did come across <a href="http://stackoverflow.com/questions/220187/algorithms-or-libraries-for-textual-analysis-specifically-dominant-words-phras">one other question</a> on the topic and I'm digging through those resources now.</p>
9
2009-07-17T00:05:09Z
1,140,928
<p>This is a really really complicated topic. Generally, this sort of stuff falls under the rubric of Natural Language Processing, and tends to be tricky at best. The difficulty of this sort of stuff is precisely why there still is no completely automated system for handling customer service and the like.</p> <p>Generally, the approach to this stuff REALLY depends on precisely what your problem domain is. If you're able to winnow down the problem domain, you can gain some very serious benefits; to use your example, if you're able to determine that your problem domain is baseball, then that gives you a really strong head start. Even then, it's a LOT of work to get anything particularly useful going.</p> <p>For what it's worth, yes, an existing corpus of words is going to be useful. More importantly, determining the functional complexity expected of the system is going to be critical; do you need to parse simple sentences, or is there a need for parsing complex behavior? Can you constrain the inputs to a relatively simple set?</p>
1
2009-07-17T00:10:30Z
[ "python", "parsing", "nlp", "lexical-analysis" ]
Parsing Meaning from Text
1,140,908
<p>I realize this is a broad topic, but I'm looking for a good primer on parsing meaning from text, ideally in Python. As an example of what I'm looking to do, if a user makes a blog post like:</p> <p>"Manny Ramirez makes his return for the Dodgers today against the Houston Astros",</p> <p>what's a light-weight/ easy way of getting the nouns out of a sentence? To start, I think I'd limit it to proper nouns, but I wouldn't want to be limited to just that (and I don't want to rely on a simple regex that assumes anything Title Capped is a proper noun).</p> <p>To make this question even worse, what are the things I'm not asking that I should be? Do I need a corpus of existing words to get started? What lexical analysis stuff do I need to know to make this work? I did come across <a href="http://stackoverflow.com/questions/220187/algorithms-or-libraries-for-textual-analysis-specifically-dominant-words-phras">one other question</a> on the topic and I'm digging through those resources now.</p>
9
2009-07-17T00:05:09Z
1,140,930
<p>What you want is called NP (noun phrase) chunking, or extraction.</p> <p><a href="http://nlp.stanford.edu/links/statnlp.html" rel="nofollow">Some links here</a></p> <p>As pointed out, this is very problem domain specific stuff. The more you can narrow it down, the more effective it will be. And you're going to have to train your program on your specific domain.</p>
3
2009-07-17T00:11:58Z
[ "python", "parsing", "nlp", "lexical-analysis" ]
Parsing Meaning from Text
1,140,908
<p>I realize this is a broad topic, but I'm looking for a good primer on parsing meaning from text, ideally in Python. As an example of what I'm looking to do, if a user makes a blog post like:</p> <p>"Manny Ramirez makes his return for the Dodgers today against the Houston Astros",</p> <p>what's a light-weight/ easy way of getting the nouns out of a sentence? To start, I think I'd limit it to proper nouns, but I wouldn't want to be limited to just that (and I don't want to rely on a simple regex that assumes anything Title Capped is a proper noun).</p> <p>To make this question even worse, what are the things I'm not asking that I should be? Do I need a corpus of existing words to get started? What lexical analysis stuff do I need to know to make this work? I did come across <a href="http://stackoverflow.com/questions/220187/algorithms-or-libraries-for-textual-analysis-specifically-dominant-words-phras">one other question</a> on the topic and I'm digging through those resources now.</p>
9
2009-07-17T00:05:09Z
1,140,931
<p>Here is the book I stumbled upon recently: <a href="http://rads.stackoverflow.com/amzn/click/0596516495" rel="nofollow">Natural Language Processing with Python</a> </p>
4
2009-07-17T00:12:15Z
[ "python", "parsing", "nlp", "lexical-analysis" ]
Parsing Meaning from Text
1,140,908
<p>I realize this is a broad topic, but I'm looking for a good primer on parsing meaning from text, ideally in Python. As an example of what I'm looking to do, if a user makes a blog post like:</p> <p>"Manny Ramirez makes his return for the Dodgers today against the Houston Astros",</p> <p>what's a light-weight/ easy way of getting the nouns out of a sentence? To start, I think I'd limit it to proper nouns, but I wouldn't want to be limited to just that (and I don't want to rely on a simple regex that assumes anything Title Capped is a proper noun).</p> <p>To make this question even worse, what are the things I'm not asking that I should be? Do I need a corpus of existing words to get started? What lexical analysis stuff do I need to know to make this work? I did come across <a href="http://stackoverflow.com/questions/220187/algorithms-or-libraries-for-textual-analysis-specifically-dominant-words-phras">one other question</a> on the topic and I'm digging through those resources now.</p>
9
2009-07-17T00:05:09Z
1,140,938
<p>Natural Language Processing (NLP) is the name for parsing, well, natural language. Many algorithms and heuristics exist, and it's an active field of research. Whatever algorithm you will code, it will need to be trained on a corpus. Just like a human: we learn a language by reading text written by other people (and/or by listening to sentences uttered by other people).</p> <p>In practical terms, have a look at the <a href="http://www.nltk.org/">Natural Language Toolkit</a>. For a theoretical underpinning of whatever you are going to code, you may want to check out <a href="http://nlp.stanford.edu/fsnlp/">Foundations of Statistical Natural Language Processing</a> by Chris Manning and Hinrich Schütze.</p> <p><img src="http://nlp.stanford.edu/fsnlp/fsnlp-bigger.jpg" alt="alt text" /></p>
7
2009-07-17T00:15:09Z
[ "python", "parsing", "nlp", "lexical-analysis" ]
Parsing Meaning from Text
1,140,908
<p>I realize this is a broad topic, but I'm looking for a good primer on parsing meaning from text, ideally in Python. As an example of what I'm looking to do, if a user makes a blog post like:</p> <p>"Manny Ramirez makes his return for the Dodgers today against the Houston Astros",</p> <p>what's a light-weight/ easy way of getting the nouns out of a sentence? To start, I think I'd limit it to proper nouns, but I wouldn't want to be limited to just that (and I don't want to rely on a simple regex that assumes anything Title Capped is a proper noun).</p> <p>To make this question even worse, what are the things I'm not asking that I should be? Do I need a corpus of existing words to get started? What lexical analysis stuff do I need to know to make this work? I did come across <a href="http://stackoverflow.com/questions/220187/algorithms-or-libraries-for-textual-analysis-specifically-dominant-words-phras">one other question</a> on the topic and I'm digging through those resources now.</p>
9
2009-07-17T00:05:09Z
1,141,386
<p>Use the <a href="http://www.nltk.org/" rel="nofollow">NLTK</a>, in particular <a href="http://www.nltk.org/book/ch07.html" rel="nofollow">chapter 7 on Information Extraction.</a></p> <p>You say you want to extract meaning, and there are modules for semantic analysis, but I think IE is all you need--and honestly one of the only areas of NLP computers can handle right now.</p> <p>See sections 7.5 and 7.6 on the subtopics of Named Entity Recognition (to chunk and categorize Manny Ramerez as a person, Dodgers as a sports organization, and Houston Astros as another sports organization, or whatever suits your domain) and Relationship Extraction. There is a NER chunker that you can plugin once you have the NLTK installed. From their examples, extracting a geo-political entity (GPE) and a person:</p> <pre><code>&gt;&gt;&gt; sent = nltk.corpus.treebank.tagged_sents()[22] &gt;&gt;&gt; print nltk.ne_chunk(sent) (S The/DT (GPE U.S./NNP) is/VBZ one/CD ... according/VBG to/TO (PERSON Brooke/NNP T./NNP Mossman/NNP) ...) </code></pre> <p>Note you'll still need to know tokenization and tagging, as discussed in earlier chapters, to get your text in the right format for these IE tasks.</p>
8
2009-07-17T03:58:18Z
[ "python", "parsing", "nlp", "lexical-analysis" ]
Parsing Meaning from Text
1,140,908
<p>I realize this is a broad topic, but I'm looking for a good primer on parsing meaning from text, ideally in Python. As an example of what I'm looking to do, if a user makes a blog post like:</p> <p>"Manny Ramirez makes his return for the Dodgers today against the Houston Astros",</p> <p>what's a light-weight/ easy way of getting the nouns out of a sentence? To start, I think I'd limit it to proper nouns, but I wouldn't want to be limited to just that (and I don't want to rely on a simple regex that assumes anything Title Capped is a proper noun).</p> <p>To make this question even worse, what are the things I'm not asking that I should be? Do I need a corpus of existing words to get started? What lexical analysis stuff do I need to know to make this work? I did come across <a href="http://stackoverflow.com/questions/220187/algorithms-or-libraries-for-textual-analysis-specifically-dominant-words-phras">one other question</a> on the topic and I'm digging through those resources now.</p>
9
2009-07-17T00:05:09Z
34,146,248
<p>Regular expressions can help in some scenario. Here is a detailed example: <a href="http://twainscanning.com/whats-the-most-mentioned-scanner-on-cnet-forum/" rel="nofollow">What’s the Most Mentioned Scanner on CNET Forum</a>, which used a regular expression to find all mentioned scanners in CNET forum posts. </p> <p>In the post, a regular expression as such was used:</p> <pre><code>(?i)((?:\w+\s\w+\s(?:(?:(?:[0-9]+[a-z\-]|[a-z]+[0-9\-]|[0-9])[a-z0-9\-]*)|all-in-one|all in one)\s(\w+\s){0,1}(?:scanner|photo scanner|flatbed scanner|adf scanner|scanning|document scanner|printer scanner|portable scanner|handheld scanner|printer\/scanner))|(?:(?:scanner|photo scanner|flatbed scanner|adf scanner|scanning|document scanner|printer scanner|portable scanner|handheld scanner|printer\/scanner)\s(\w+\s){1,2}(?:(?:(?:[0-9]+[a-z\-]|[a-z]+[0-9\-]|[0-9])[a-z0-9\-]*)|all-in-one|all in one))) </code></pre> <p>in order to match either of the following:</p> <ul> <li>two words, then model number (including all-in-one), then “scanner”</li> <li>“scanner”, then one or two words, then model number (including all-in-one)</li> </ul> <p>As a result, the text extracted from the post was like,</p> <blockquote> <ol> <li>discontinued HP C9900A photo scanner</li> <li>scanning his old x-rays</li> <li>new Epson V700 scanner</li> <li>HP ScanJet 4850 scanner</li> <li>Epson Perfection 3170 scanner</li> </ol> </blockquote> <p>This regular expression solution worked in a way. </p>
-1
2015-12-08T01:04:45Z
[ "python", "parsing", "nlp", "lexical-analysis" ]
What's a quick one-liner to remove empty lines from a python string?
1,140,958
<p>I have some code in a python string that contains extraneous empty lines. I would like to remove all empty lines from the string. What's the most pythonic way to do this?</p> <p>Note: I'm not looking for a general code re-formatter, just a quick one or two-liner. </p> <p>Thanks!</p>
29
2009-07-17T00:21:12Z
1,140,966
<p>How about:</p> <pre><code>text = os.linesep.join([s for s in text.splitlines() if s]) </code></pre> <p>where <code>text</code> is the string with the possible extraneous lines?</p>
52
2009-07-17T00:25:15Z
[ "python", "string", "line-endings" ]
What's a quick one-liner to remove empty lines from a python string?
1,140,958
<p>I have some code in a python string that contains extraneous empty lines. I would like to remove all empty lines from the string. What's the most pythonic way to do this?</p> <p>Note: I'm not looking for a general code re-formatter, just a quick one or two-liner. </p> <p>Thanks!</p>
29
2009-07-17T00:21:12Z
1,140,967
<pre><code>"\n".join([s for s in code.split("\n") if s]) </code></pre> <p>Edit2:</p> <pre><code>text = "".join([s for s in code.splitlines(True) if s.strip("\r\n")]) </code></pre> <p>I think that's my final version. It should work well even with code mixing line endings. I don't think that line with spaces should be considered empty, but if so then simple s.strip() will do instead. </p>
10
2009-07-17T00:25:18Z
[ "python", "string", "line-endings" ]
What's a quick one-liner to remove empty lines from a python string?
1,140,958
<p>I have some code in a python string that contains extraneous empty lines. I would like to remove all empty lines from the string. What's the most pythonic way to do this?</p> <p>Note: I'm not looking for a general code re-formatter, just a quick one or two-liner. </p> <p>Thanks!</p>
29
2009-07-17T00:21:12Z
1,141,067
<p>This one will remove lines of spaces too.</p> <p><code>re.replace(u'(?imu)^\s*\n', u'', code)</code></p>
3
2009-07-17T01:15:55Z
[ "python", "string", "line-endings" ]
What's a quick one-liner to remove empty lines from a python string?
1,140,958
<p>I have some code in a python string that contains extraneous empty lines. I would like to remove all empty lines from the string. What's the most pythonic way to do this?</p> <p>Note: I'm not looking for a general code re-formatter, just a quick one or two-liner. </p> <p>Thanks!</p>
29
2009-07-17T00:21:12Z
1,141,893
<pre><code>filter(None, code.splitlines()) filter(str.strip, code.splitlines()) </code></pre> <p>are equivalent to</p> <pre><code>[s for s in code.splitlines() if s] [s for s in code.splitlines() if s.strip()] </code></pre> <p>and might be useful for readability</p>
10
2009-07-17T07:46:23Z
[ "python", "string", "line-endings" ]
What's a quick one-liner to remove empty lines from a python string?
1,140,958
<p>I have some code in a python string that contains extraneous empty lines. I would like to remove all empty lines from the string. What's the most pythonic way to do this?</p> <p>Note: I'm not looking for a general code re-formatter, just a quick one or two-liner. </p> <p>Thanks!</p>
29
2009-07-17T00:21:12Z
1,142,968
<p>And now for something completely different:</p> <pre><code>Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam &gt;&gt;&gt; import string, re &gt;&gt;&gt; tidy = lambda s: string.join(filter(string.strip, re.split(r'[\r\n]+', s)), '\n') &gt;&gt;&gt; tidy('\r\n \n\ra\n\n b \r\rc\n\n') 'a\012 b \012c' </code></pre> <p>Episode 2:</p> <p>This one doesn't work on 1.5 :-(</p> <p>BUT not only does it handle universal newlines and blank lines, it also removes trailing whitespace (good idea when tidying up code lines IMHO) AND does a repair job if the last meaningful line is not terminated.</p> <pre><code>import re tidy = lambda c: re.sub( r'(^\s*[\r\n]+|^\s*\Z)|(\s*\Z|\s*[\r\n]+)', lambda m: '\n' if m.lastindex == 2 else '', c) </code></pre>
0
2009-07-17T12:24:59Z
[ "python", "string", "line-endings" ]
What's a quick one-liner to remove empty lines from a python string?
1,140,958
<p>I have some code in a python string that contains extraneous empty lines. I would like to remove all empty lines from the string. What's the most pythonic way to do this?</p> <p>Note: I'm not looking for a general code re-formatter, just a quick one or two-liner. </p> <p>Thanks!</p>
29
2009-07-17T00:21:12Z
24,172,715
<p><strong>LESSON ON REMOVING NEWLINES and EMPTY LINES WITH SPACES</strong></p> <p>"t" is the variable with the text. You will see an "s" variable, its a temporary variable that only exists during the evaluation of the main set of parenthesis (forgot the name of these lil python things)</p> <p>First lets set the "t" variable so it has new lines:</p> <pre><code>&gt;&gt;&gt; t='hi there here is\na big line\n\nof empty\nline\neven some with spaces\n \nlike that\n\n \nokay now what?\n' </code></pre> <p>Note there is another way to set the varible using triple quotes</p> <pre><code>somevar=""" asdfas asdf asdf asdf asdf """" </code></pre> <p>Here is how it looks when we view it without "print":</p> <pre><code>&gt;&gt;&gt; t 'hi there here is\na big line\n\nof empty\nline\neven some with spaces\n \nlike that\n\n \nokay now what?\n' </code></pre> <p>To see with actual newlines, print it.</p> <pre><code>&gt;&gt;&gt; print t hi there here is a big line of empty line even some with spaces like that okay now what? </code></pre> <p><strong>COMMAND REMOVE ALL BLANK LINES (INCLUDING SPACES):</strong></p> <p>So somelines newlines are just newlines, and some have spaces so they look like new lines</p> <p>If you want to get rid of all blank looking lines (if they have just newlines, or spaces as well)</p> <pre><code>&gt;&gt;&gt; print "".join([s for s in t.strip().splitlines(True) if s.strip()]) hi there here is a big line of empty line even some with spaces like that okay now what? </code></pre> <p>OR:</p> <pre><code>&gt;&gt;&gt; print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n").strip()]) hi there here is a big line of empty line even some with spaces like that okay now what? </code></pre> <p>NOTE: that strip in t.strip().splitline(True) can be removes so its just t.splitlines(True), but then your output can end with an extra newline (so that removes the final newline). The strip() in the last part s.strip("\r\n").strip() and s.strip() is what actually removes the spaces in newlines and newlines.</p> <p><strong>COMMAND REMOVE ALL BLANK LINES (BUT NOT ONES WITH SPACES):</strong></p> <p>Technically lines with spaces should NOT be considered empty, but it all depends on the use case and what your trying to achieve.</p> <pre><code>&gt;&gt;&gt; print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n")]) hi there here is a big line of empty line even some with spaces like that okay now what? </code></pre> <p>** NOTE ABOUT THAT MIDDLE strip **</p> <p>That middle strip there, thats attached to the "t" variable, just removes the last newline (just as the previous note has stated). Here is how it would look like without that strip being there (notice that last newline)</p> <p>With 1st example (removing newlines and newlines with spaces)</p> <pre><code>&gt;&gt;&gt; print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n").strip()]) hi there here is a big line of empty line even some with spaces like that okay now what? .without strip new line here (stackoverflow cant have me format it in). </code></pre> <p>With 2nd example (removing newlines only)</p> <pre><code>&gt;&gt;&gt; print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n")]) hi there here is a big line of empty line even some with spaces like that okay now what? .without strip new line here (stackoverflow cant have me format it in). </code></pre> <p>The END!</p>
6
2014-06-11T21:16:55Z
[ "python", "string", "line-endings" ]
Traversing a Python object tree
1,141,039
<p>I'm trying to implement dynamic reloading objects in Python, that reflect code changes live.</p> <p>Modules reloading is working, but I have to recreate every instance of the modules' classes for changes to become effective.</p> <p>The problem is that objects data (objects <code>__dict__</code> content) is lost during the process.</p> <p>So I tried another approach:</p> <pre><code>def refresh(obj, memo=None): if memo is None: memo = {} d = id(obj) if d in memo: return memo[d] = None try: obj.__class__ = getattr(sys.modules[obj.__class__.__module__], obj.__class__.__name__) except TypeError: return for item in obj.__dict__.itervalues(): if isinstance(item, dict): for k, v in item.iteritems(): refresh(k, memo) refresh(v, memo) elif isinstance(item, (list, tuple)): for v in item: refresh(v, memo) else: refresh(item, memo) </code></pre> <p>And surprisingly it works ! After calling refresh() on my objects, the new code becomes effective, without need to recreate them.</p> <p>But I'm not sure if this is the correct way to traverse an object ? Is there a better way to traverse an object's components ?</p>
1
2009-07-17T00:59:26Z
1,141,199
<p>See <a href="http://code.activestate.com/recipes/160164/" rel="nofollow">this recipe</a> in the Python Cookbook (or maybe even better its version in the "printed" one, which I believe you can actually read for free with google book search, or for sure on O'Reilly's "Safari" site using a free 1-week trial subscription -- I did a lot of editing on Hudson's original recipe to get the "printed book" version!).</p>
1
2009-07-17T02:24:12Z
[ "python", "reload", "traversal" ]