title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Dynamic loading of python modules | 951,124 | <p>In python how do you dynamically add modules to a package while your programming is running.</p>
<p>I want to be able to add modules to the package directory from an outside process, and be able to use those new modules in my program:</p>
<pre><code>import package
def doSomething(name):
pkg = __import__("package." + name)
mod = getattr(pkg, name)
mod.doSomething()
</code></pre>
<p>How do I do this?</p>
| 32 | 2009-06-04T14:59:25Z | 951,256 | <p>Your code is almost correct.</p>
<p>See <a href="http://docs.python.org/library/functions.html#__import__"><code>__import__</code></a> function.</p>
<pre><code>def doSomething(name):
name = "package." + name
mod = __import__(name, fromlist=[''])
mod.doSomething()
</code></pre>
| 38 | 2009-06-04T15:25:02Z | [
"python",
"dynamic",
"python-import"
] |
Dynamic loading of python modules | 951,124 | <p>In python how do you dynamically add modules to a package while your programming is running.</p>
<p>I want to be able to add modules to the package directory from an outside process, and be able to use those new modules in my program:</p>
<pre><code>import package
def doSomething(name):
pkg = __import__("package." + name)
mod = getattr(pkg, name)
mod.doSomething()
</code></pre>
<p>How do I do this?</p>
| 32 | 2009-06-04T14:59:25Z | 951,268 | <p>To detect changes to a directory, on Linux, you can use <a href="http://trac.dbzteam.org/pyinotify" rel="nofollow">pyinotify</a> (<a href="http://david-latham.blogspot.com/2008/06/python-inotify-pyinotify-how-to-watch.html" rel="nofollow">here</a> is a nice working example); on a Mac, <a href="http://www.wilcoxd.com/blog/pyobjc-20-fsevents.html" rel="nofollow">fsevents</a> (via the PyObjC package that comes with your Mac); on Windows, <a href="http://timgolden.me.uk/python/win32%5Fhow%5Fdo%5Fi/watch%5Fdirectory%5Ffor%5Fchanges.html" rel="nofollow">Directory Change Notifications</a> via <a href="http://python.net/crew/mhammond/win32/" rel="nofollow">win32api</a> (or the Python standard library <code>ctypes</code> module). AFAIK, nobody's wrapped up these various approaches into one portable package. (Of course, worst case, you can fall back to "lower tech" approaches such as periodic polling, as <a href="http://timgolden.me.uk/python/win32%5Fhow%5Fdo%5Fi/watch%5Fdirectory%5Ffor%5Fchanges.html" rel="nofollow">Tim Golden's article</a>, perhaps with a touch of "alerts from an external process" via a signal, etc).</p>
<p>Once you do have the notification and the name of the new or modified module, the code you show in the question should work.</p>
| 3 | 2009-06-04T15:26:31Z | [
"python",
"dynamic",
"python-import"
] |
Dynamic loading of python modules | 951,124 | <p>In python how do you dynamically add modules to a package while your programming is running.</p>
<p>I want to be able to add modules to the package directory from an outside process, and be able to use those new modules in my program:</p>
<pre><code>import package
def doSomething(name):
pkg = __import__("package." + name)
mod = getattr(pkg, name)
mod.doSomething()
</code></pre>
<p>How do I do this?</p>
| 32 | 2009-06-04T14:59:25Z | 951,678 | <p>Bastien already answered the question, anyway you may find useful this function I use to load all the modules from a subfolder in a dictionary:</p>
<pre><code>def loadModules():
res = {}
import os
# check subfolders
lst = os.listdir("services")
dir = []
for d in lst:
s = os.path.abspath("services") + os.sep + d
if os.path.isdir(s) and os.path.exists(s + os.sep + "__init__.py"):
dir.append(d)
# load the modules
for d in dir:
res[d] = __import__("services." + d, fromlist = ["*"])
return res
</code></pre>
<p>This other one is to instantiate an object by a class defined in one of the modules loaded by the first function:</p>
<pre><code>def getClassByName(module, className):
if not module:
if className.startswith("services."):
className = className.split("services.")[1]
l = className.split(".")
m = __services__[l[0]]
return getClassByName(m, ".".join(l[1:]))
elif "." in className:
l = className.split(".")
m = getattr(module, l[0])
return getClassByName(m, ".".join(l[1:]))
else:
return getattr(module, className)
</code></pre>
<p>A simple way to use those functions is this:</p>
<pre><code>mods = loadModules()
cls = getClassByName(mods["MyModule"], "submodule.filepy.Class")
obj = cls()
</code></pre>
<p>Obviously you can replace all the "services" subfolder references with parameters.</p>
| 16 | 2009-06-04T16:33:38Z | [
"python",
"dynamic",
"python-import"
] |
Dynamic loading of python modules | 951,124 | <p>In python how do you dynamically add modules to a package while your programming is running.</p>
<p>I want to be able to add modules to the package directory from an outside process, and be able to use those new modules in my program:</p>
<pre><code>import package
def doSomething(name):
pkg = __import__("package." + name)
mod = getattr(pkg, name)
mod.doSomething()
</code></pre>
<p>How do I do this?</p>
| 32 | 2009-06-04T14:59:25Z | 951,846 | <p>One trick with Bastien's answer... The <code>__import__()</code> function returns the package object, not the module object. If you use the following function, it will dynamically load the module from the package and return you the module, not the package.</p>
<pre><code>def my_import(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
</code></pre>
<p>Then you can do:</p>
<pre><code>mod = my_import('package.' + name)
mod.doSomething()
</code></pre>
| 8 | 2009-06-04T17:02:57Z | [
"python",
"dynamic",
"python-import"
] |
How to build a fully-customizable application (aka database), without lose performance/good-design? | 951,387 | <p>im in the beginning of the complete restyle of an my web application, and i have some doubt about a good database-design that can be reliable, query-performance, and in the same time fully customizable by the users (users wont customize the database structure, but the funcionality of the application).</p>
<p>So, my actual situation is, for example, a simple user's table:</p>
<pre><code>id | name | surname | nickname | email | phone
1 | foo | bar | foobar | foo@bar.com | 99999
</code></pre>
<p>Thats it.</p>
<p>But, lets say that one of my customer would like to have 2 email addresses, or phone numbers, for one specific user.</p>
<p>Untill now, i used to solve that problem simply adding columns in the users table:</p>
<pre><code>id | name | surname | nickname | email | phone | email_two | phone_two
1 | foo | bar | foobar | foo@bar.com | 99999 | foo@bar.net | 999998
</code></pre>
<p>But i cant use that way with the new application's version.. i'll like to be drinking mojito after that, dont like costumer's call to edit the structure :)</p>
<p>So, i thought a solution where people can define customs field, simply with another table:</p>
<pre><code>id | table_refer | type_field | id_object | value
1 | users | phone | 1 | 999998
2 | users | email | 1 | foo@bar.net
</code></pre>
<p>keeping the users table unaltered.</p>
<p>But this way have 2 problems:</p>
<ol>
<li>For what i know, there is no possibility to use foreigns key in that way, that if i delete 1 user automatically the foreign key delete in cascade all the row in the second table that have the 'table_refer' value=users and the id_object=users.id. Sure, i'll can use some triggers function, but i'll lose some of the reliability.</li>
<li>When i'll need to query the database, fore retrieve the users that match 'foo@bar.net', i'll have to check all the... hem.. option_table as well, and that will make my code complex and less-reliable and messy with many joins.. assuming that the users table wont be the only one 'extended' by the 'option_table', seem to be a gray view.</li>
</ol>
<p>My goal is to let my customers adding as many custom fields as they need, for almost all the object in the application (users, items, invoices, print views, photos, news, etc...), assuming that most of those table would be partitioned (splitted in 2 table, with a 3 table and inheritance gerarchy).</p>
<p>You think my way can be good, do you know some other better, or am i in a big mistake?
Please, every suggest is gold now!</p>
<p><strong>EDIT</strong>: </p>
<p>What i'm lookin for could be simplifyed ith the 'articles-custom-fields' in wordpress blogs.
My goal is to let the user to define new fields that he needs, for example, if my users table is the one above, and a customer need a field that i havent prevent, like the web-site url, he must be able to add it dinamically, without edit the database structure, but just the data.</p>
<p>I think that the 2° table (maibe 1 for each object) can be a good solution, but i am still waiting for better ways!</p>
| 1 | 2009-06-04T15:45:52Z | 951,423 | <p>if you do it this way all of your queries will have to join to and use table_refer column, which will kill performance, and make simple queries hard, and hard queries very difficult.</p>
<p>if your want multiple e-mails, split the email out to another table so you can have many rows.</p>
| 0 | 2009-06-04T15:51:52Z | [
"php",
"python",
"performance",
"database-design",
"postgresql"
] |
How to build a fully-customizable application (aka database), without lose performance/good-design? | 951,387 | <p>im in the beginning of the complete restyle of an my web application, and i have some doubt about a good database-design that can be reliable, query-performance, and in the same time fully customizable by the users (users wont customize the database structure, but the funcionality of the application).</p>
<p>So, my actual situation is, for example, a simple user's table:</p>
<pre><code>id | name | surname | nickname | email | phone
1 | foo | bar | foobar | foo@bar.com | 99999
</code></pre>
<p>Thats it.</p>
<p>But, lets say that one of my customer would like to have 2 email addresses, or phone numbers, for one specific user.</p>
<p>Untill now, i used to solve that problem simply adding columns in the users table:</p>
<pre><code>id | name | surname | nickname | email | phone | email_two | phone_two
1 | foo | bar | foobar | foo@bar.com | 99999 | foo@bar.net | 999998
</code></pre>
<p>But i cant use that way with the new application's version.. i'll like to be drinking mojito after that, dont like costumer's call to edit the structure :)</p>
<p>So, i thought a solution where people can define customs field, simply with another table:</p>
<pre><code>id | table_refer | type_field | id_object | value
1 | users | phone | 1 | 999998
2 | users | email | 1 | foo@bar.net
</code></pre>
<p>keeping the users table unaltered.</p>
<p>But this way have 2 problems:</p>
<ol>
<li>For what i know, there is no possibility to use foreigns key in that way, that if i delete 1 user automatically the foreign key delete in cascade all the row in the second table that have the 'table_refer' value=users and the id_object=users.id. Sure, i'll can use some triggers function, but i'll lose some of the reliability.</li>
<li>When i'll need to query the database, fore retrieve the users that match 'foo@bar.net', i'll have to check all the... hem.. option_table as well, and that will make my code complex and less-reliable and messy with many joins.. assuming that the users table wont be the only one 'extended' by the 'option_table', seem to be a gray view.</li>
</ol>
<p>My goal is to let my customers adding as many custom fields as they need, for almost all the object in the application (users, items, invoices, print views, photos, news, etc...), assuming that most of those table would be partitioned (splitted in 2 table, with a 3 table and inheritance gerarchy).</p>
<p>You think my way can be good, do you know some other better, or am i in a big mistake?
Please, every suggest is gold now!</p>
<p><strong>EDIT</strong>: </p>
<p>What i'm lookin for could be simplifyed ith the 'articles-custom-fields' in wordpress blogs.
My goal is to let the user to define new fields that he needs, for example, if my users table is the one above, and a customer need a field that i havent prevent, like the web-site url, he must be able to add it dinamically, without edit the database structure, but just the data.</p>
<p>I think that the 2° table (maibe 1 for each object) can be a good solution, but i am still waiting for better ways!</p>
| 1 | 2009-06-04T15:45:52Z | 951,431 | <p>As I said in my <a href="http://stackoverflow.com/questions/885096/how-to-design-db-table-schema-with-ease/885135#885135">Answer</a> to a similar question, "Database Design is Hard." You are going to have to make the decision about which is better for you, normalizing the tables and bringing phone numbers and e-mail addresses into their own tables, with the associated JOIN-ing to retrieve the data, and the extra effort of referential integrity, or having some number <em>n</em> e-mail and phone fields in your table, and the "data-messiness" that that entails. </p>
<p>Database design is always a series of tradeoffs. You need to look at all angles, maybe bodge up some prototypes and do some profiling, etc. There is no "One True Answerâ¢".</p>
| 4 | 2009-06-04T15:53:15Z | [
"php",
"python",
"performance",
"database-design",
"postgresql"
] |
How to build a fully-customizable application (aka database), without lose performance/good-design? | 951,387 | <p>im in the beginning of the complete restyle of an my web application, and i have some doubt about a good database-design that can be reliable, query-performance, and in the same time fully customizable by the users (users wont customize the database structure, but the funcionality of the application).</p>
<p>So, my actual situation is, for example, a simple user's table:</p>
<pre><code>id | name | surname | nickname | email | phone
1 | foo | bar | foobar | foo@bar.com | 99999
</code></pre>
<p>Thats it.</p>
<p>But, lets say that one of my customer would like to have 2 email addresses, or phone numbers, for one specific user.</p>
<p>Untill now, i used to solve that problem simply adding columns in the users table:</p>
<pre><code>id | name | surname | nickname | email | phone | email_two | phone_two
1 | foo | bar | foobar | foo@bar.com | 99999 | foo@bar.net | 999998
</code></pre>
<p>But i cant use that way with the new application's version.. i'll like to be drinking mojito after that, dont like costumer's call to edit the structure :)</p>
<p>So, i thought a solution where people can define customs field, simply with another table:</p>
<pre><code>id | table_refer | type_field | id_object | value
1 | users | phone | 1 | 999998
2 | users | email | 1 | foo@bar.net
</code></pre>
<p>keeping the users table unaltered.</p>
<p>But this way have 2 problems:</p>
<ol>
<li>For what i know, there is no possibility to use foreigns key in that way, that if i delete 1 user automatically the foreign key delete in cascade all the row in the second table that have the 'table_refer' value=users and the id_object=users.id. Sure, i'll can use some triggers function, but i'll lose some of the reliability.</li>
<li>When i'll need to query the database, fore retrieve the users that match 'foo@bar.net', i'll have to check all the... hem.. option_table as well, and that will make my code complex and less-reliable and messy with many joins.. assuming that the users table wont be the only one 'extended' by the 'option_table', seem to be a gray view.</li>
</ol>
<p>My goal is to let my customers adding as many custom fields as they need, for almost all the object in the application (users, items, invoices, print views, photos, news, etc...), assuming that most of those table would be partitioned (splitted in 2 table, with a 3 table and inheritance gerarchy).</p>
<p>You think my way can be good, do you know some other better, or am i in a big mistake?
Please, every suggest is gold now!</p>
<p><strong>EDIT</strong>: </p>
<p>What i'm lookin for could be simplifyed ith the 'articles-custom-fields' in wordpress blogs.
My goal is to let the user to define new fields that he needs, for example, if my users table is the one above, and a customer need a field that i havent prevent, like the web-site url, he must be able to add it dinamically, without edit the database structure, but just the data.</p>
<p>I think that the 2° table (maibe 1 for each object) can be a good solution, but i am still waiting for better ways!</p>
| 1 | 2009-06-04T15:45:52Z | 951,439 | <p>You could design your application to request additional data (like emails list for the user) on demand, using AJAX etc. In those highly customizable and rich applications usually you have no need to display all the data - only a single category. </p>
<p>To store custom records you can create table <code>field_types(id, name, datatype)</code> and a table <code>custom_fields(user_id, field_type_id, value)</code>, and then select smth like this: </p>
<p><code>SELECT * FROM custom_fields WHERE user_id=XXX AND field_type_id IN (X,Y,Z)</code>.</p>
<p>so now you can retrieve data in 1 fast query, split fields to categories and parse their values by their respective datatypes with your code without performance issues.</p>
| 0 | 2009-06-04T15:55:15Z | [
"php",
"python",
"performance",
"database-design",
"postgresql"
] |
How to build a fully-customizable application (aka database), without lose performance/good-design? | 951,387 | <p>im in the beginning of the complete restyle of an my web application, and i have some doubt about a good database-design that can be reliable, query-performance, and in the same time fully customizable by the users (users wont customize the database structure, but the funcionality of the application).</p>
<p>So, my actual situation is, for example, a simple user's table:</p>
<pre><code>id | name | surname | nickname | email | phone
1 | foo | bar | foobar | foo@bar.com | 99999
</code></pre>
<p>Thats it.</p>
<p>But, lets say that one of my customer would like to have 2 email addresses, or phone numbers, for one specific user.</p>
<p>Untill now, i used to solve that problem simply adding columns in the users table:</p>
<pre><code>id | name | surname | nickname | email | phone | email_two | phone_two
1 | foo | bar | foobar | foo@bar.com | 99999 | foo@bar.net | 999998
</code></pre>
<p>But i cant use that way with the new application's version.. i'll like to be drinking mojito after that, dont like costumer's call to edit the structure :)</p>
<p>So, i thought a solution where people can define customs field, simply with another table:</p>
<pre><code>id | table_refer | type_field | id_object | value
1 | users | phone | 1 | 999998
2 | users | email | 1 | foo@bar.net
</code></pre>
<p>keeping the users table unaltered.</p>
<p>But this way have 2 problems:</p>
<ol>
<li>For what i know, there is no possibility to use foreigns key in that way, that if i delete 1 user automatically the foreign key delete in cascade all the row in the second table that have the 'table_refer' value=users and the id_object=users.id. Sure, i'll can use some triggers function, but i'll lose some of the reliability.</li>
<li>When i'll need to query the database, fore retrieve the users that match 'foo@bar.net', i'll have to check all the... hem.. option_table as well, and that will make my code complex and less-reliable and messy with many joins.. assuming that the users table wont be the only one 'extended' by the 'option_table', seem to be a gray view.</li>
</ol>
<p>My goal is to let my customers adding as many custom fields as they need, for almost all the object in the application (users, items, invoices, print views, photos, news, etc...), assuming that most of those table would be partitioned (splitted in 2 table, with a 3 table and inheritance gerarchy).</p>
<p>You think my way can be good, do you know some other better, or am i in a big mistake?
Please, every suggest is gold now!</p>
<p><strong>EDIT</strong>: </p>
<p>What i'm lookin for could be simplifyed ith the 'articles-custom-fields' in wordpress blogs.
My goal is to let the user to define new fields that he needs, for example, if my users table is the one above, and a customer need a field that i havent prevent, like the web-site url, he must be able to add it dinamically, without edit the database structure, but just the data.</p>
<p>I think that the 2° table (maibe 1 for each object) can be a good solution, but i am still waiting for better ways!</p>
| 1 | 2009-06-04T15:45:52Z | 951,507 | <p>I'm not sure about the specifics of postgresql, but if you want highly customisable data structures in a DB that you don't really want to search on, the s<a href="http://martinfowler.com/eaaCatalog/serializedLOB.html" rel="nofollow">erializing the data to a LOB</a> is an option.</p>
<p>In fact this is the way ASP.NET works by default with Personalization, which is per user settings.</p>
<p>I don't recommend this approach if you wish to search the fields for any reason.</p>
| 0 | 2009-06-04T16:08:26Z | [
"php",
"python",
"performance",
"database-design",
"postgresql"
] |
How to build a fully-customizable application (aka database), without lose performance/good-design? | 951,387 | <p>im in the beginning of the complete restyle of an my web application, and i have some doubt about a good database-design that can be reliable, query-performance, and in the same time fully customizable by the users (users wont customize the database structure, but the funcionality of the application).</p>
<p>So, my actual situation is, for example, a simple user's table:</p>
<pre><code>id | name | surname | nickname | email | phone
1 | foo | bar | foobar | foo@bar.com | 99999
</code></pre>
<p>Thats it.</p>
<p>But, lets say that one of my customer would like to have 2 email addresses, or phone numbers, for one specific user.</p>
<p>Untill now, i used to solve that problem simply adding columns in the users table:</p>
<pre><code>id | name | surname | nickname | email | phone | email_two | phone_two
1 | foo | bar | foobar | foo@bar.com | 99999 | foo@bar.net | 999998
</code></pre>
<p>But i cant use that way with the new application's version.. i'll like to be drinking mojito after that, dont like costumer's call to edit the structure :)</p>
<p>So, i thought a solution where people can define customs field, simply with another table:</p>
<pre><code>id | table_refer | type_field | id_object | value
1 | users | phone | 1 | 999998
2 | users | email | 1 | foo@bar.net
</code></pre>
<p>keeping the users table unaltered.</p>
<p>But this way have 2 problems:</p>
<ol>
<li>For what i know, there is no possibility to use foreigns key in that way, that if i delete 1 user automatically the foreign key delete in cascade all the row in the second table that have the 'table_refer' value=users and the id_object=users.id. Sure, i'll can use some triggers function, but i'll lose some of the reliability.</li>
<li>When i'll need to query the database, fore retrieve the users that match 'foo@bar.net', i'll have to check all the... hem.. option_table as well, and that will make my code complex and less-reliable and messy with many joins.. assuming that the users table wont be the only one 'extended' by the 'option_table', seem to be a gray view.</li>
</ol>
<p>My goal is to let my customers adding as many custom fields as they need, for almost all the object in the application (users, items, invoices, print views, photos, news, etc...), assuming that most of those table would be partitioned (splitted in 2 table, with a 3 table and inheritance gerarchy).</p>
<p>You think my way can be good, do you know some other better, or am i in a big mistake?
Please, every suggest is gold now!</p>
<p><strong>EDIT</strong>: </p>
<p>What i'm lookin for could be simplifyed ith the 'articles-custom-fields' in wordpress blogs.
My goal is to let the user to define new fields that he needs, for example, if my users table is the one above, and a customer need a field that i havent prevent, like the web-site url, he must be able to add it dinamically, without edit the database structure, but just the data.</p>
<p>I think that the 2° table (maibe 1 for each object) can be a good solution, but i am still waiting for better ways!</p>
| 1 | 2009-06-04T15:45:52Z | 951,546 | <p>Your proposed model is composed of two database patterns: an <a href="http://en.wikipedia.org/wiki/Entity-attribute-value%5Fmodel" rel="nofollow">entity-attribute-value table</a> and a <a href="http://en.wikipedia.org/wiki/Polymorphic%5Fassociation" rel="nofollow">polymorphic association</a>.</p>
<p>Entity-attribute-value has some pretty big issues both in the performance and data integrity department. If you don't need to access the additional attributes in queries, then you can serialize the attribute value mapping to a text field in some standard serialization (JSON, XML). Not "pure" from the database design standpoint, but possibly a good pragmatic choice, given that you are aware of the tradeoffs. On postgres you can also use the hstore contrib module to store key-value pairs to make it usable in queries, if the limitation of string only values is acceptable.</p>
<p>For polymorphic association, you can get referential integrity by introducing an association table:</p>
<pre><code>users attrib_assocs custom_attribs
----- ------------- --------------
attrib_assoc_id --> id <-- assoc_id
... entity_type field
value
</code></pre>
<p>To get slightly more integrity, also add the entity_type to the primary key and corresponding foreign keys and a check constraint on users table that the entity_type equals 'user'.</p>
| 1 | 2009-06-04T16:13:02Z | [
"php",
"python",
"performance",
"database-design",
"postgresql"
] |
sudoku obfuscated python -> perl translation | 951,666 | <p>Anybody care to translate this into obfuscated perl? It's written in Python taken from: <a href="http://stackoverflow.com/questions/201461/shortest-sudoku-solver-in-python-how-does-it-work">here</a></p>
<pre><code>def r(a):i=a.find('0');~i or exit(a);[m
in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for
j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import*;r(argv[1])
</code></pre>
<p>I realize it's just for fun :)</p>
| 1 | 2009-06-04T16:30:55Z | 951,684 | <p>There already are a few Sudoku solvers written in Obfuscated Perl, do you really want another (possibly less efficient) one?</p>
<p>If not...</p>
<ol>
<li>De-obfuscate.</li>
<li>Rewrite in Perl.</li>
<li>Obfuscate.</li>
</ol>
| 2 | 2009-06-04T16:36:19Z | [
"python",
"perl",
"translate"
] |
sudoku obfuscated python -> perl translation | 951,666 | <p>Anybody care to translate this into obfuscated perl? It's written in Python taken from: <a href="http://stackoverflow.com/questions/201461/shortest-sudoku-solver-in-python-how-does-it-work">here</a></p>
<pre><code>def r(a):i=a.find('0');~i or exit(a);[m
in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for
j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import*;r(argv[1])
</code></pre>
<p>I realize it's just for fun :)</p>
| 1 | 2009-06-04T16:30:55Z | 952,137 | <pre><code>sub r{($a=shift)=~/0/g?my$i=pos:die$a;T:for$m(1..9){($i-$_)%9*(int($i/9)^int($_/9))*(int($i/27)^int($_/27)|int($i%9/3)^int($_%9/3))||$a=~/^.{$_}$m/&&next T,for 0..80;substr($a,$i,1)=$m;r($a)}}r@ARGV
</code></pre>
<p>The braindead translation. Longer, since Python 2's <code>/</code> is integer division while Perl's is floating-point.</p>
| 3 | 2009-06-04T17:56:56Z | [
"python",
"perl",
"translate"
] |
caching issues in MySQL response with MySQLdb in Django | 952,216 | <p>I use MySQL with MySQLdb module in Python, in Django.</p>
<p>I'm running in autocommit mode in this case (and Django's transaction.is_managed() actually returns False).</p>
<p>I have several processes interacting with the database. </p>
<p>One process fetches all Task models with Task.objects.all()</p>
<p>Then another process adds a Task model (I can see it in a database management application).</p>
<p>If I call Task.objects.all() on the first process, I don't see anything. But if I call connection._commit() and then Task.objects.all(), I see the new Task.</p>
<p>My question is: Is there any caching involved at connection level? And is it a normal behaviour (it does not seems to me)?</p>
| 2 | 2009-06-04T18:13:14Z | 952,424 | <p>This certainly seems autocommit/table locking - related.</p>
<p>If mysqldb implements the dbapi2 spec it will probably have a connection running as one single continuous transaction. When you say: <code>'running in autocommit mode'</code>: do you mean MySQL itself or the mysqldb module? Or Django?</p>
<p><em>Not intermittently commiting perfectly explains the behaviour you are getting:</em></p>
<p><strong>i)</strong> a connection implemented as one single transaction in mysqldb (by default, probably)</p>
<p><strong>ii)</strong> not opening/closing connections only when needed but (re)using one (or more) persistent database connections (my guess, could be Django-architecture-inherited).</p>
<p><strong>ii)</strong> your selects ('reads') cause a 'simple read lock' on a table (which means other connections can still 'read' this table but connections wanting to 'write data' can't (immediately) because this lock prevents them from getting an 'exclusive lock' (needed 'for writing') on this table. The writing is thus postponed indefinitely (until it can get a (short) exclusive lock on the table for writing - when you close the connection or manually commit).</p>
<p>I'd do the following in your case:</p>
<ul>
<li>find out which table locks are on your database during the scenario above</li>
<li><a href="http://docs.djangoproject.com/en/dev/topics/db/transactions/" rel="nofollow">read about Django and transactions here</a>. A quick skim suggests using standard Django functionality implicitely causes commits. This means sending handcrafted SQL maybe won't (insert, update...).</li>
</ul>
| 1 | 2009-06-04T18:54:12Z | [
"python",
"mysql",
"django",
"connection",
"commit"
] |
How to sort based on dependencies? | 952,302 | <p>I have an class that has a list of "dependencies" pointing to other classes of the same base type.</p>
<pre><code>class Foo(Base):
dependencies = []
class Bar(Base):
dependencies = [Foo]
class Baz(Base):
dependencies = [Bar]
</code></pre>
<p>I'd like to sort the instances these classes generate based on their dependencies. In my example I'd expect instances of Foo to come first, then Bar, then Baz.</p>
<p>What's the best way to sort this?</p>
| 7 | 2009-06-04T18:31:25Z | 952,388 | <p>It's called a topological sort.</p>
<pre><code>def sort_deps(objs):
queue = [objs with no dependencies]
while queue:
obj = queue.pop()
yield obj
for obj in objs:
if dependencies are now satisfied:
queue.append(obj)
if not all dependencies are satisfied:
error
return result
</code></pre>
| 15 | 2009-06-04T18:47:11Z | [
"python",
"sorting",
"dependencies"
] |
How to sort based on dependencies? | 952,302 | <p>I have an class that has a list of "dependencies" pointing to other classes of the same base type.</p>
<pre><code>class Foo(Base):
dependencies = []
class Bar(Base):
dependencies = [Foo]
class Baz(Base):
dependencies = [Bar]
</code></pre>
<p>I'd like to sort the instances these classes generate based on their dependencies. In my example I'd expect instances of Foo to come first, then Bar, then Baz.</p>
<p>What's the best way to sort this?</p>
| 7 | 2009-06-04T18:31:25Z | 952,856 | <p>I had a similar question just last week - wish I'd know about Stack Overflow then! I hunted around a bit until I realized that I had a <em>DAG</em> (Directed <strong>Acyclic</strong> Graph since my dependencies couldn't be recursive or circular). Then I found a few references for algorithms to sort them. I used a depth-first traversal to get to the leaf nodes and add them to sorted list first.</p>
<p>Here's a page that I found useful:</p>
<p><a href="http://www.allisons.org/ll/AlgDS/Graph/DAG/">Directed Acyclic Graphs</a></p>
| 5 | 2009-06-04T20:18:09Z | [
"python",
"sorting",
"dependencies"
] |
Inferring appropriate database type declarations from strings in Python | 952,541 | <p>I am building some Postgres tables from Python dictionaries where the {'key': 'value'} pairs correspond to column 'key' and field 'value'. These are generated from .dbf files -- I now pipe the contents of the .dbf files into a script that returns a list of dicts like:</p>
<pre><code>{'Warngentyp': '', 'Lon': '-81.67170', 'Zwatch_war': '0', 'State':...
</code></pre>
<p>Currently I am putting these into a sqlite database with no type declarations, then dumping it to a .sql file, manually editing the schema, and importing to Postgres.</p>
<p>I would love to be able to infer the correct type declarations, basically iterate over a list of strings like ['0', '3', '5'] or ['ga', 'ca', 'tn'] or ['-81.009', '135.444', '-80.000'] and generate something like 'int', 'varchar(2)', 'float'. (I would be equally happy with a Python, Postgres, or SQLite tool.)</p>
<p>Is there a package that does this, or a straightforward way to implement it? </p>
| 1 | 2009-06-04T19:14:58Z | 952,588 | <p>You can determine integers and floats unsafely by <code>type(eval(elem))</code>, where <code>elem</code> is an element of the list. (But then you need to check elem for possible bad code)</p>
<p>A safer way could be to do the following</p>
<pre><code>a = ['24.2', '.2', '2']
try:
if all(elem.isdigit() for elem in a):
print("int")
elif all(float(elem) for elem in a):
print("float")
except:
i = len(a[0])
if all(len(elem)==i for elem in a):
print("varchar(%s)"%i)
else:
print "n/a"
</code></pre>
| 1 | 2009-06-04T19:21:43Z | [
"python",
"sqlite",
"postgresql",
"types"
] |
Inferring appropriate database type declarations from strings in Python | 952,541 | <p>I am building some Postgres tables from Python dictionaries where the {'key': 'value'} pairs correspond to column 'key' and field 'value'. These are generated from .dbf files -- I now pipe the contents of the .dbf files into a script that returns a list of dicts like:</p>
<pre><code>{'Warngentyp': '', 'Lon': '-81.67170', 'Zwatch_war': '0', 'State':...
</code></pre>
<p>Currently I am putting these into a sqlite database with no type declarations, then dumping it to a .sql file, manually editing the schema, and importing to Postgres.</p>
<p>I would love to be able to infer the correct type declarations, basically iterate over a list of strings like ['0', '3', '5'] or ['ga', 'ca', 'tn'] or ['-81.009', '135.444', '-80.000'] and generate something like 'int', 'varchar(2)', 'float'. (I would be equally happy with a Python, Postgres, or SQLite tool.)</p>
<p>Is there a package that does this, or a straightforward way to implement it? </p>
| 1 | 2009-06-04T19:14:58Z | 952,618 | <p>Don't use eval. If someone inserts bad code, it can hose your database or server.</p>
<p>Instead use these</p>
<pre><code>def isFloat(s):
try:
float(s)
return True
except (ValueError, TypeError), e:
return False
str.isdigit()
</code></pre>
<p>And everything else can be a varchar</p>
| 5 | 2009-06-04T19:26:18Z | [
"python",
"sqlite",
"postgresql",
"types"
] |
Inferring appropriate database type declarations from strings in Python | 952,541 | <p>I am building some Postgres tables from Python dictionaries where the {'key': 'value'} pairs correspond to column 'key' and field 'value'. These are generated from .dbf files -- I now pipe the contents of the .dbf files into a script that returns a list of dicts like:</p>
<pre><code>{'Warngentyp': '', 'Lon': '-81.67170', 'Zwatch_war': '0', 'State':...
</code></pre>
<p>Currently I am putting these into a sqlite database with no type declarations, then dumping it to a .sql file, manually editing the schema, and importing to Postgres.</p>
<p>I would love to be able to infer the correct type declarations, basically iterate over a list of strings like ['0', '3', '5'] or ['ga', 'ca', 'tn'] or ['-81.009', '135.444', '-80.000'] and generate something like 'int', 'varchar(2)', 'float'. (I would be equally happy with a Python, Postgres, or SQLite tool.)</p>
<p>Is there a package that does this, or a straightforward way to implement it? </p>
| 1 | 2009-06-04T19:14:58Z | 958,621 | <p>Thanks for the help, this is a little long for an update, here is how I combined the answers. I am starting with a list of dicts like this, generated from a dbf file:</p>
<pre><code>dbf_list = [{'Warngentyp': '', 'Lon': '-81.67170', 'Zwatch_war': '0', 'State':...
</code></pre>
<p>Then a function that returns 1000 values per column to test for the best db type declaration: <code>{'column_name':['list', 'of', 'sample', 'values'], 'col2':['1','2','3','4'...</code> like this:</p>
<pre><code>def sample_fields(dicts_, number=1000): #dicts_ would be dbf_list from above
sample = dict([[item, []] for item in dicts_[1]])
for dict_ in dicts_[:number]:
for col_ in dict_:
sample[col_].append(dict_[col_])
return sample
</code></pre>
<p>Then you combine the Unknown and jacob approach: varchar is a good default and floats and ints are basically enough for everything else, <code>all</code> is clear and fast:</p>
<pre><code>def find_typedefs(sample_dict): #arg is output of previous function
defs_ = {}
for key in sample_dict:
defs_[key] = 'varchar(255)'
try:
if all([int(value) for value in sample_dict[key]]):
defs_[key] = 'int'
except:
try:
if all([float(value) for value in sample_dict[key]]):
defs_[key] = 'float'
except:
continue
return defs_
</code></pre>
<p>Then format the returned dict into a <code>create table</code> statement, iterate over the values in the original big list and feed them into the database. It works great, I am now skipping the intermediate sqlite step, thanks again.</p>
<p>Update for John Machin: I am using the shp2pgsql library distributed with PostGIS. It creates schema like the below with a source like <a href="http://www.weather.gov/geodata/catalog/national/html/cities.htm" rel="nofollow">this one</a>:</p>
<pre><code> Column | Type |
------------+-----------------------+-
gid | integer |
st_fips | character varying(7) |
sfips | character varying(5) |
county_fip | character varying(12) |
cfips | character varying(6) |
pl_fips | character varying(7) |
id | character varying(7) |
elevation | character varying(11) |
pop_1990 | integer |
population | character varying(12) |
name | character varying(32) |
st | character varying(12) |
state | character varying(16) |
warngenlev | character varying(13) |
warngentyp | character varying(13) |
watch_warn | character varying(14) |
zwatch_war | bigint |
prog_disc | bigint |
zprog_disc | bigint |
comboflag | bigint |
land_water | character varying(13) |
recnum | integer |
lon | numeric |
lat | numeric |
the_geom | geometry |
</code></pre>
<p>There is stuff there that has to be wrong -- Fips is the federal information processing standard, and it should be an integer between 0 and something like 100,000. Population, elevation, etc. Maybe I have more of a postgres specific question, I wouldn't mind loosing a small amount of data, or pushing it into a table for errors or something, while trying to change the type on say the population field. How strict is the dbf type checking? For example I see that population per shp2pgsql is varchar(12). Is it possible that some small percentage of population fields contain something like '2,445 Est.'? If I take the approach I set out in this question, with the first thousand records, I get a schema like this:</p>
<pre><code> Column | Type |
------------+------------------------+-
warngentyp | character varying(255) |
lon | double precision |
zwatch_war | character varying(255) |
state | character varying(255) |
recnum | character varying(255) |
pop_1990 | integer |
land_water | character varying(255) |
elevation | integer |
prog_disc | integer |
comboflag | character varying(255) |
sfips | integer |
zprog_disc | integer |
pl_fips | integer |
county_fip | integer |
population | integer |
watch_warn | integer |
name | character varying(255) |
st | character varying(255) |
lat | double precision |
st_fips | integer |
cfips | integer |
id | integer |
warngenlev | integer |
</code></pre>
<p>On the other hand if I check every value in the all(['list', 'of', 'everything'...]), I get a schema more like the first one. I can tolerate a bit of data loss here -- if the entry for some town is wrong and it doesn't significantly affect the population figures, etc.</p>
<p>I am only using an old package called <code>dbview</code> to pipe the dbf files into these scripts -- I am not trying to map any of the format's native capability. I assumed that shp2pgsql would have picked the low-hanging fruit in that regard. Any suggestions for either dbview or another package is welcome -- although there are other cases where I may not be working with dbf files and would need to find the best types anyway. I am also going to ask a question about postgresql to see if I can find a solution at that level.</p>
| 1 | 2009-06-06T00:01:24Z | [
"python",
"sqlite",
"postgresql",
"types"
] |
Inferring appropriate database type declarations from strings in Python | 952,541 | <p>I am building some Postgres tables from Python dictionaries where the {'key': 'value'} pairs correspond to column 'key' and field 'value'. These are generated from .dbf files -- I now pipe the contents of the .dbf files into a script that returns a list of dicts like:</p>
<pre><code>{'Warngentyp': '', 'Lon': '-81.67170', 'Zwatch_war': '0', 'State':...
</code></pre>
<p>Currently I am putting these into a sqlite database with no type declarations, then dumping it to a .sql file, manually editing the schema, and importing to Postgres.</p>
<p>I would love to be able to infer the correct type declarations, basically iterate over a list of strings like ['0', '3', '5'] or ['ga', 'ca', 'tn'] or ['-81.009', '135.444', '-80.000'] and generate something like 'int', 'varchar(2)', 'float'. (I would be equally happy with a Python, Postgres, or SQLite tool.)</p>
<p>Is there a package that does this, or a straightforward way to implement it? </p>
| 1 | 2009-06-04T19:14:58Z | 959,882 | <p>YOU DON'T NEED TO INFER THE TYPE DECLARATIONS!!!</p>
<p>You can derive what you want directly from the .dbf files. Each column has a name, a type code (C=Character, N=Number, D=Date (yyyymmdd), L=Logical (T/F), plus more types if the files are from Foxpro), a length (where relevant), and a number of decimal places (for type N). </p>
<p>Whatever software that you used to dig the data out of the .dbf files needed to use that information to convert each piece of data to the appropriate Python data type.</p>
<p>Dictionaries? Why? With a minor amount of work, that software could be modified to produce a CREATE TABLE statement based on those column definitions, plus an INSERT statement for each row of data.</p>
<p>I presume you are using one of the several published Python DBF-reading modules. Any one of them should have the facilities that you need: open a .dbf file, get the column names, get the column type etc info, get each row of data. If you are unhappy with the module that you are using, talk to me; I have an unpublished one that as far as reading DBFs goes, combines the better features of the others, avoids the worst features, is as fast as you'll get with a pure Python implementation, handles all the Visual Foxpro datatypes and the _NullFlags pseudo-column, handles memoes, etc etc.</p>
<p>HTH</p>
<p>=========
Addendum:
When I said you didn't need to infer types, you hadn't made it plain that you had a bunch of fields of type C which contained numbers.</p>
<p>FIPS fields: some are with and some without leading zeroes. If you are going to use them, you face the '012' != '12' != 12 problem. I'd suggest stripping off the leading zeroes and keeping them in integer columns, restoring leading zeroes in reports or whatever if you really need to. Why are there 2 each of state fips and county fips?</p>
<p>Population: in the sample file, almost all are integer. Four are like 40552.0000, and a reasonable number are blank/empty. You seem to regard population as important, and asked "Is it possible that some small percentage of population fields contain .... ?" Anything is possible in data. Don't wonder and speculate, investigate! I'd strongly advise you to sort your data in population order and eyeball it; you'll find that multiple places in the same state share the same population count. E.g. There are 35 places in New York state whose pop'n is stated as 8,008,278; they are spread over 6 counties. 29 of them have a PL_FIPS value of 51000; 5 have 5100 -- looks like a trailing zero problem :-(</p>
<p>Tip for deciding between float and int: try anum = float(chars) <em>first</em>; if that succeeds, check if int(anum) == anum.</p>
<p>ID: wonderful "unique ID"; 59 cases where it's not an int -- several in Canada (the website said "US cities"; is this an artifact of some unresolved border dispute?), some containing the word 'Number', and some empty.</p>
<p>Low-hanging fruit: I would have thought that deducing that population was in fact integer was 0.1 inches above the ground :-)</p>
<p>There's a serious flaw in that if all([int(value) ... logic:</p>
<pre><code>>>> all([int(value) for value in "0 1 2 3 4 5 6 7 8 9".split()])
False
>>> all([int(value) for value in "1 2 3 4 5 6 7 8 9".split()])
True
>>>
</code></pre>
<p>You evidently think that you are testing that all the strings can be converted to int, but you're adding the rider "and are all non-zero". Ditto float a few lines later.</p>
<p>IOW if there's just one zero value, you declare that the column is not integer.
Even after fixing that, if there's just one empty value, you call it varchar.
What I suggest is: count how many are empty (after normalising whitespace (which should include NBSP)), how many qualify as integer, how many non-integer non-empty ones qualify as float, and how many "other". Check the "other" ones; decide whether to reject or fix; repeat until happy :-)</p>
<p>I hope some of this helps.</p>
| 2 | 2009-06-06T15:03:41Z | [
"python",
"sqlite",
"postgresql",
"types"
] |
Help me find an appropriate ruby/python parser generator | 952,648 | <p>The first parser generator I've worked with was Parse::RecDescent, and the guides/tutorials available for it were great, but the most useful feature it has was it's debugging tools, specifically the <b>tracing</b> capabilities ( activated by setting $RD_TRACE to 1 ). I am looking for a parser generator that can help you debug it's rules.</p>
<p>The thing is, it has to be written in python or in ruby, and have a verbose mode/trace mode or very helpful debugging techniques.</p>
<p>Does anyone know such a parser generator ?</p>
<p>EDIT: when I said debugging, I wasn't referring to debugging python or ruby. I was referring to debugging the parser generator, see what it's doing at every step, see every char it's reading, rules it's trying to match. Hope you get the point.</p>
<p><b>BOUNTY EDIT: to win the bounty, please show a parser generator framework, and illustrate some of it's debugging features. I repeat, I'm not interested in pdb, but in parser's debugging framework. Also, please don't mention treetop. I'm not interested in it.</b></p>
| 5 | 2009-06-04T19:34:32Z | 952,680 | <p>Python wiki has a <a href="http://wiki.python.org/moin/LanguageParsing" rel="nofollow">list</a> of Language Parsers written in Python.</p>
| 0 | 2009-06-04T19:40:21Z | [
"python",
"ruby",
"debugging",
"parser-generator"
] |
Help me find an appropriate ruby/python parser generator | 952,648 | <p>The first parser generator I've worked with was Parse::RecDescent, and the guides/tutorials available for it were great, but the most useful feature it has was it's debugging tools, specifically the <b>tracing</b> capabilities ( activated by setting $RD_TRACE to 1 ). I am looking for a parser generator that can help you debug it's rules.</p>
<p>The thing is, it has to be written in python or in ruby, and have a verbose mode/trace mode or very helpful debugging techniques.</p>
<p>Does anyone know such a parser generator ?</p>
<p>EDIT: when I said debugging, I wasn't referring to debugging python or ruby. I was referring to debugging the parser generator, see what it's doing at every step, see every char it's reading, rules it's trying to match. Hope you get the point.</p>
<p><b>BOUNTY EDIT: to win the bounty, please show a parser generator framework, and illustrate some of it's debugging features. I repeat, I'm not interested in pdb, but in parser's debugging framework. Also, please don't mention treetop. I'm not interested in it.</b></p>
| 5 | 2009-06-04T19:34:32Z | 952,785 | <p>Python is a pretty easy language to debug. You can just do import pdb pdb.settrace().</p>
<p>However, these parser generators supposedly come with good debugging facilities.</p>
<p><a href="http://www.antlr.org/">http://www.antlr.org/</a></p>
<p><a href="http://www.dabeaz.com/ply/">http://www.dabeaz.com/ply/</a></p>
<p><a href="http://pyparsing.wikispaces.com/">http://pyparsing.wikispaces.com/</a></p>
<p><strong>In response to bounty</strong></p>
<p>Here is PLY debugging in action.</p>
<p>Source Code</p>
<pre><code>tokens = (
'NAME','NUMBER',
)
literals = ['=','+','-','*','/', '(',')']
# Tokens
t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'
def t_NUMBER(t):
r'\d+'
t.value = int(t.value)
return t
t_ignore = " \t"
def t_newline(t):
r'\n+'
t.lexer.lineno += t.value.count("\n")
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
# Build the lexer
import ply.lex as lex
lex.lex(debug=1)
# Parsing rules
precedence = (
('left','+','-'),
('left','*','/'),
('right','UMINUS'),
)
# dictionary of names
names = { }
def p_statement_assign(p):
'statement : NAME "=" expression'
names[p[1]] = p[3]
def p_statement_expr(p):
'statement : expression'
print(p[1])
def p_expression_binop(p):
'''expression : expression '+' expression
| expression '-' expression
| expression '*' expression
| expression '/' expression'''
if p[2] == '+' : p[0] = p[1] + p[3]
elif p[2] == '-': p[0] = p[1] - p[3]
elif p[2] == '*': p[0] = p[1] * p[3]
elif p[2] == '/': p[0] = p[1] / p[3]
def p_expression_uminus(p):
"expression : '-' expression %prec UMINUS"
p[0] = -p[2]
def p_expression_group(p):
"expression : '(' expression ')'"
p[0] = p[2]
def p_expression_number(p):
"expression : NUMBER"
p[0] = p[1]
def p_expression_name(p):
"expression : NAME"
try:
p[0] = names[p[1]]
except LookupError:
print("Undefined name '%s'" % p[1])
p[0] = 0
def p_error(p):
if p:
print("Syntax error at '%s'" % p.value)
else:
print("Syntax error at EOF")
import ply.yacc as yacc
yacc.yacc()
import logging
logging.basicConfig(
level=logging.INFO,
filename="parselog.txt"
)
while 1:
try:
s = raw_input('calc > ')
except EOFError:
break
if not s: continue
yacc.parse(s, debug=1)
</code></pre>
<p>Output</p>
<pre><code>lex: tokens = ('NAME', 'NUMBER')
lex: literals = ['=', '+', '-', '*', '/', '(', ')']
lex: states = {'INITIAL': 'inclusive'}
lex: Adding rule t_NUMBER -> '\d+' (state 'INITIAL')
lex: Adding rule t_newline -> '\n+' (state 'INITIAL')
lex: Adding rule t_NAME -> '[a-zA-Z_][a-zA-Z0-9_]*' (state 'INITIAL')
lex: ==== MASTER REGEXS FOLLOW ====
lex: state 'INITIAL' : regex[0] = '(?P<t_NUMBER>\d+)|(?P<t_newline>\n+)|(?P<t_NAME>[a-zA-Z
_][a-zA-Z0-9_]*)'
calc > 2+3
PLY: PARSE DEBUG START
State : 0
Stack : . LexToken(NUMBER,2,1,0)
Action : Shift and goto state 3
State : 3
Stack : NUMBER . LexToken(+,'+',1,1)
Action : Reduce rule [expression -> NUMBER] with [2] and goto state 9
Result : <int @ 0x1a1896c> (2)
State : 6
Stack : expression . LexToken(+,'+',1,1)
Action : Shift and goto state 12
State : 12
Stack : expression + . LexToken(NUMBER,3,1,2)
Action : Shift and goto state 3
State : 3
Stack : expression + NUMBER . $end
Action : Reduce rule [expression -> NUMBER] with [3] and goto state 9
Result : <int @ 0x1a18960> (3)
State : 18
Stack : expression + expression . $end
Action : Reduce rule [expression -> expression + expression] with [2,'+',3] and goto state
3
Result : <int @ 0x1a18948> (5)
State : 6
Stack : expression . $end
Action : Reduce rule [statement -> expression] with [5] and goto state 2
5
Result : <NoneType @ 0x1e1ccef4> (None)
State : 4
Stack : statement . $end
Done : Returning <NoneType @ 0x1e1ccef4> (None)
PLY: PARSE DEBUG END
calc >
</code></pre>
<p>Parse Table generated at parser.out</p>
<pre><code>Created by PLY version 3.2 (http://www.dabeaz.com/ply)
Grammar
Rule 0 S' -> statement
Rule 1 statement -> NAME = expression
Rule 2 statement -> expression
Rule 3 expression -> expression + expression
Rule 4 expression -> expression - expression
Rule 5 expression -> expression * expression
Rule 6 expression -> expression / expression
Rule 7 expression -> - expression
Rule 8 expression -> ( expression )
Rule 9 expression -> NUMBER
Rule 10 expression -> NAME
Terminals, with rules where they appear
( : 8
) : 8
* : 5
+ : 3
- : 4 7
/ : 6
= : 1
NAME : 1 10
NUMBER : 9
error :
Nonterminals, with rules where they appear
expression : 1 2 3 3 4 4 5 5 6 6 7 8
statement : 0
Parsing method: LALR
state 0
(0) S' -> . statement
(1) statement -> . NAME = expression
(2) statement -> . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
NAME shift and go to state 1
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
expression shift and go to state 6
statement shift and go to state 4
state 1
(1) statement -> NAME . = expression
(10) expression -> NAME .
= shift and go to state 7
+ reduce using rule 10 (expression -> NAME .)
- reduce using rule 10 (expression -> NAME .)
* reduce using rule 10 (expression -> NAME .)
/ reduce using rule 10 (expression -> NAME .)
$end reduce using rule 10 (expression -> NAME .)
state 2
(7) expression -> - . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 9
state 3
(9) expression -> NUMBER .
+ reduce using rule 9 (expression -> NUMBER .)
- reduce using rule 9 (expression -> NUMBER .)
* reduce using rule 9 (expression -> NUMBER .)
/ reduce using rule 9 (expression -> NUMBER .)
$end reduce using rule 9 (expression -> NUMBER .)
) reduce using rule 9 (expression -> NUMBER .)
state 4
(0) S' -> statement .
state 5
(8) expression -> ( . expression )
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 10
state 6
(2) statement -> expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
$end reduce using rule 2 (statement -> expression .)
+ shift and go to state 12
- shift and go to state 11
* shift and go to state 13
/ shift and go to state 14
state 7
(1) statement -> NAME = . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 15
state 8
(10) expression -> NAME .
+ reduce using rule 10 (expression -> NAME .)
- reduce using rule 10 (expression -> NAME .)
* reduce using rule 10 (expression -> NAME .)
/ reduce using rule 10 (expression -> NAME .)
$end reduce using rule 10 (expression -> NAME .)
) reduce using rule 10 (expression -> NAME .)
state 9
(7) expression -> - expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
+ reduce using rule 7 (expression -> - expression .)
- reduce using rule 7 (expression -> - expression .)
* reduce using rule 7 (expression -> - expression .)
/ reduce using rule 7 (expression -> - expression .)
$end reduce using rule 7 (expression -> - expression .)
) reduce using rule 7 (expression -> - expression .)
! + [ shift and go to state 12 ]
! - [ shift and go to state 11 ]
! * [ shift and go to state 13 ]
! / [ shift and go to state 14 ]
state 10
(8) expression -> ( expression . )
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
) shift and go to state 16
+ shift and go to state 12
- shift and go to state 11
* shift and go to state 13
/ shift and go to state 14
state 11
(4) expression -> expression - . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 17
state 12
(3) expression -> expression + . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 18
state 13
(5) expression -> expression * . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 19
state 14
(6) expression -> expression / . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 20
state 15
(1) statement -> NAME = expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
$end reduce using rule 1 (statement -> NAME = expression .)
+ shift and go to state 12
- shift and go to state 11
* shift and go to state 13
/ shift and go to state 14
state 16
(8) expression -> ( expression ) .
+ reduce using rule 8 (expression -> ( expression ) .)
- reduce using rule 8 (expression -> ( expression ) .)
* reduce using rule 8 (expression -> ( expression ) .)
/ reduce using rule 8 (expression -> ( expression ) .)
$end reduce using rule 8 (expression -> ( expression ) .)
) reduce using rule 8 (expression -> ( expression ) .)
state 17
(4) expression -> expression - expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
+ reduce using rule 4 (expression -> expression - expression .)
- reduce using rule 4 (expression -> expression - expression .)
$end reduce using rule 4 (expression -> expression - expression .)
) reduce using rule 4 (expression -> expression - expression .)
* shift and go to state 13
/ shift and go to state 14
! * [ reduce using rule 4 (expression -> expression - expression .) ]
! / [ reduce using rule 4 (expression -> expression - expression .) ]
! + [ shift and go to state 12 ]
! - [ shift and go to state 11 ]
state 18
(3) expression -> expression + expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
+ reduce using rule 3 (expression -> expression + expression .)
- reduce using rule 3 (expression -> expression + expression .)
$end reduce using rule 3 (expression -> expression + expression .)
) reduce using rule 3 (expression -> expression + expression .)
* shift and go to state 13
/ shift and go to state 14
! * [ reduce using rule 3 (expression -> expression + expression .) ]
! / [ reduce using rule 3 (expression -> expression + expression .) ]
! + [ shift and go to state 12 ]
! - [ shift and go to state 11 ]
state 19
(5) expression -> expression * expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
+ reduce using rule 5 (expression -> expression * expression .)
- reduce using rule 5 (expression -> expression * expression .)
* reduce using rule 5 (expression -> expression * expression .)
/ reduce using rule 5 (expression -> expression * expression .)
$end reduce using rule 5 (expression -> expression * expression .)
) reduce using rule 5 (expression -> expression * expression .)
! + [ shift and go to state 12 ]
! - [ shift and go to state 11 ]
! * [ shift and go to state 13 ]
! / [ shift and go to state 14 ]
state 20
(6) expression -> expression / expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
+ reduce using rule 6 (expression -> expression / expression .)
- reduce using rule 6 (expression -> expression / expression .)
* reduce using rule 6 (expression -> expression / expression .)
/ reduce using rule 6 (expression -> expression / expression .)
$end reduce using rule 6 (expression -> expression / expression .)
) reduce using rule 6 (expression -> expression / expression .)
! + [ shift and go to state 12 ]
! - [ shift and go to state 11 ]
! * [ shift and go to state 13 ]
! / [ shift and go to state 14 ]
</code></pre>
| 6 | 2009-06-04T20:02:20Z | [
"python",
"ruby",
"debugging",
"parser-generator"
] |
Help me find an appropriate ruby/python parser generator | 952,648 | <p>The first parser generator I've worked with was Parse::RecDescent, and the guides/tutorials available for it were great, but the most useful feature it has was it's debugging tools, specifically the <b>tracing</b> capabilities ( activated by setting $RD_TRACE to 1 ). I am looking for a parser generator that can help you debug it's rules.</p>
<p>The thing is, it has to be written in python or in ruby, and have a verbose mode/trace mode or very helpful debugging techniques.</p>
<p>Does anyone know such a parser generator ?</p>
<p>EDIT: when I said debugging, I wasn't referring to debugging python or ruby. I was referring to debugging the parser generator, see what it's doing at every step, see every char it's reading, rules it's trying to match. Hope you get the point.</p>
<p><b>BOUNTY EDIT: to win the bounty, please show a parser generator framework, and illustrate some of it's debugging features. I repeat, I'm not interested in pdb, but in parser's debugging framework. Also, please don't mention treetop. I'm not interested in it.</b></p>
| 5 | 2009-06-04T19:34:32Z | 983,823 | <p>I don't know anything about its debugging features, but I've heard good things about PyParsing.</p>
<p><a href="http://pyparsing.wikispaces.com/" rel="nofollow">http://pyparsing.wikispaces.com/</a></p>
| 2 | 2009-06-11T21:29:55Z | [
"python",
"ruby",
"debugging",
"parser-generator"
] |
Help me find an appropriate ruby/python parser generator | 952,648 | <p>The first parser generator I've worked with was Parse::RecDescent, and the guides/tutorials available for it were great, but the most useful feature it has was it's debugging tools, specifically the <b>tracing</b> capabilities ( activated by setting $RD_TRACE to 1 ). I am looking for a parser generator that can help you debug it's rules.</p>
<p>The thing is, it has to be written in python or in ruby, and have a verbose mode/trace mode or very helpful debugging techniques.</p>
<p>Does anyone know such a parser generator ?</p>
<p>EDIT: when I said debugging, I wasn't referring to debugging python or ruby. I was referring to debugging the parser generator, see what it's doing at every step, see every char it's reading, rules it's trying to match. Hope you get the point.</p>
<p><b>BOUNTY EDIT: to win the bounty, please show a parser generator framework, and illustrate some of it's debugging features. I repeat, I'm not interested in pdb, but in parser's debugging framework. Also, please don't mention treetop. I'm not interested in it.</b></p>
| 5 | 2009-06-04T19:34:32Z | 1,408,667 | <p>I know the bounty has already been claimed, but here is an equivalent parser written in pyparsing (plus support for function calls with zero or more comma-delimted arguments):</p>
<pre><code>from pyparsing import *
LPAR, RPAR = map(Suppress,"()")
EQ = Literal("=")
name = Word(alphas, alphanums+"_").setName("name")
number = Word(nums).setName("number")
expr = Forward()
operand = Optional('-') + (Group(name + LPAR +
Group(Optional(delimitedList(expr))) +
RPAR) |
name |
number |
Group(LPAR + expr + RPAR))
binop = oneOf("+ - * / **")
expr << (Group(operand + OneOrMore(binop + operand)) | operand)
assignment = name + EQ + expr
statement = assignment | expr
</code></pre>
<p>This test code runs the parser through its basic paces:</p>
<pre><code>tests = """\
sin(pi/2)
y = mx+b
E = mc ** 2
F = m*a
x = x0 + v*t +a*t*t/2
1 - sqrt(sin(t)**2 + cos(t)**2)""".splitlines()
for t in tests:
print t.strip()
print statement.parseString(t).asList()
print
</code></pre>
<p>Gives this output:</p>
<pre><code>sin(pi/2)
[['sin', [['pi', '/', '2']]]]
y = mx+b
['y', '=', ['mx', '+', 'b']]
E = mc ** 2
['E', '=', ['mc', '**', '2']]
F = m*a
['F', '=', ['m', '*', 'a']]
x = x0 + v*t +a*t*t/2
['x', '=', ['x0', '+', 'v', '*', 't', '+', 'a', '*', 't', '*', 't', '/', '2']]
1 - sqrt(sin(t)**2 + cos(t)**2)
[['1', '-', ['sqrt', [[['sin', ['t']], '**', '2', '+', ['cos', ['t']], '**', '2']]]]]
</code></pre>
<p>For debugging, we add this code:</p>
<pre><code># enable debugging for name and number expressions
name.setDebug()
number.setDebug()
</code></pre>
<p>And now we reparse the first test (displaying the input string and a simple column ruler):</p>
<pre><code>t = tests[0]
print ("1234567890"*10)[:len(t)]
print t
statement.parseString(t)
print
</code></pre>
<p>Giving this output:</p>
<pre><code>1234567890123
sin(pi/2)
Match name at loc 4(1,5)
Matched name -> ['sin']
Match name at loc 4(1,5)
Matched name -> ['sin']
Match name at loc 8(1,9)
Matched name -> ['pi']
Match name at loc 8(1,9)
Matched name -> ['pi']
Match name at loc 11(1,12)
Exception raised:Expected name (at char 11), (line:1, col:12)
Match name at loc 11(1,12)
Exception raised:Expected name (at char 11), (line:1, col:12)
Match number at loc 11(1,12)
Matched number -> ['2']
Match name at loc 4(1,5)
Matched name -> ['sin']
Match name at loc 8(1,9)
Matched name -> ['pi']
Match name at loc 8(1,9)
Matched name -> ['pi']
Match name at loc 11(1,12)
Exception raised:Expected name (at char 11), (line:1, col:12)
Match name at loc 11(1,12)
Exception raised:Expected name (at char 11), (line:1, col:12)
Match number at loc 11(1,12)
Matched number -> ['2']
</code></pre>
<p>Pyparsing also supports packrat parsing, a sort of parse-time memoization (read more about packratting <a href="http://pyparsing-public.wikispaces.com/FAQs#toc3" rel="nofollow" title="packrat parsing">here</a>). Here is the same parsing sequence, but with packrat enabled:</p>
<pre><code>same parse, but with packrat parsing enabled
1234567890123
sin(pi/2)
Match name at loc 4(1,5)
Matched name -> ['sin']
Match name at loc 8(1,9)
Matched name -> ['pi']
Match name at loc 8(1,9)
Matched name -> ['pi']
Match name at loc 11(1,12)
Exception raised:Expected name (at char 11), (line:1, col:12)
Match name at loc 11(1,12)
Exception raised:Expected name (at char 11), (line:1, col:12)
Match number at loc 11(1,12)
Matched number -> ['2']
</code></pre>
<p>This was an interesting exercise, and helpful to me to see debugging features from other parser libraries.</p>
| 2 | 2009-09-11T02:08:14Z | [
"python",
"ruby",
"debugging",
"parser-generator"
] |
Help me find an appropriate ruby/python parser generator | 952,648 | <p>The first parser generator I've worked with was Parse::RecDescent, and the guides/tutorials available for it were great, but the most useful feature it has was it's debugging tools, specifically the <b>tracing</b> capabilities ( activated by setting $RD_TRACE to 1 ). I am looking for a parser generator that can help you debug it's rules.</p>
<p>The thing is, it has to be written in python or in ruby, and have a verbose mode/trace mode or very helpful debugging techniques.</p>
<p>Does anyone know such a parser generator ?</p>
<p>EDIT: when I said debugging, I wasn't referring to debugging python or ruby. I was referring to debugging the parser generator, see what it's doing at every step, see every char it's reading, rules it's trying to match. Hope you get the point.</p>
<p><b>BOUNTY EDIT: to win the bounty, please show a parser generator framework, and illustrate some of it's debugging features. I repeat, I'm not interested in pdb, but in parser's debugging framework. Also, please don't mention treetop. I'm not interested in it.</b></p>
| 5 | 2009-06-04T19:34:32Z | 2,475,183 | <p>ANTLR above has the advantage to generate human readable and understandable code,
since it is (a very sophisticated and powerful) top-down parser,
so you can step through it with a regular debugger
and see what it <em>really</em> is doing.</p>
<p>That's why it is my parser generator of choice.</p>
<p>Bottom up parser generators like PLY have the disadvantage
that for larger grammars it is almost impossible to understand
what the debugging output really means and why the
parsing table is like it is.</p>
| 1 | 2010-03-19T05:37:38Z | [
"python",
"ruby",
"debugging",
"parser-generator"
] |
Making a flat list out of list of lists in Python | 952,914 | <p>I wonder whether there is a shortcut to make a simple list out of list of lists in Python.</p>
<p>I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with <em>reduce</em>, but I get an error.</p>
<p><strong>Code</strong></p>
<pre><code>l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
</code></pre>
<p><strong>Error message</strong></p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
</code></pre>
| 1,039 | 2009-06-04T20:30:05Z | 952,943 | <pre><code>>>> l = [[1,2,3],[4,5,6], [7], [8,9]]
>>> reduce(lambda x,y: x+y,l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>The <code>extend()</code> method in your example modifies <code>x</code> instead of returning a useful value (which <code>reduce()</code> expects).</p>
<p>A faster way to do the <code>reduce</code> version would be</p>
<pre><code>>>> import operator
>>> l = [[1,2,3],[4,5,6], [7], [8,9]]
>>> reduce(operator.add, l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
| 46 | 2009-06-04T20:35:30Z | [
"python",
"list"
] |
Making a flat list out of list of lists in Python | 952,914 | <p>I wonder whether there is a shortcut to make a simple list out of list of lists in Python.</p>
<p>I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with <em>reduce</em>, but I get an error.</p>
<p><strong>Code</strong></p>
<pre><code>l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
</code></pre>
<p><strong>Error message</strong></p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
</code></pre>
| 1,039 | 2009-06-04T20:30:05Z | 952,946 | <pre><code>>>> sum(l, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>Note that only works on lists of lists. For lists of lists of lists, you'll need another solution.</p>
| 375 | 2009-06-04T20:35:53Z | [
"python",
"list"
] |
Making a flat list out of list of lists in Python | 952,914 | <p>I wonder whether there is a shortcut to make a simple list out of list of lists in Python.</p>
<p>I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with <em>reduce</em>, but I get an error.</p>
<p><strong>Code</strong></p>
<pre><code>l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
</code></pre>
<p><strong>Error message</strong></p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
</code></pre>
| 1,039 | 2009-06-04T20:30:05Z | 952,952 | <pre><code>[item for sublist in l for item in sublist]
</code></pre>
<p>is faster than the shortcuts posted so far. (<code>l</code> is the list to flatten.)</p>
<p>For evidence, as always, you can use the <code>timeit</code> module in the standard library:</p>
<pre><code>$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'
10000 loops, best of 3: 143 usec per loop
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'
1000 loops, best of 3: 969 usec per loop
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)'
1000 loops, best of 3: 1.1 msec per loop
</code></pre>
<p>Explanation: the shortcuts based on <code>+</code> (including the implied use in <code>sum</code>) are, of necessity, <code>O(L**2)</code> when there are L sublists -- as the intermediate result list keeps getting longer, at each step a new intermediate result list object gets allocated, and all the items in the previous intermediate result must be copied over (as well as a few new ones added at the end). So (for simplicity and without actual loss of generality) say you have L sublists of I items each: the first I items are copied back and forth L-1 times, the second I items L-2 times, and so on; total number of copies is I times the sum of x for x from 1 to L excluded, i.e., <code>I * (L**2)/2</code>.</p>
<p>The list comprehension just generates one list, once, and copies each item over (from its original place of residence to the result list) also exactly once.</p>
| 1,587 | 2009-06-04T20:37:01Z | [
"python",
"list"
] |
Making a flat list out of list of lists in Python | 952,914 | <p>I wonder whether there is a shortcut to make a simple list out of list of lists in Python.</p>
<p>I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with <em>reduce</em>, but I get an error.</p>
<p><strong>Code</strong></p>
<pre><code>l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
</code></pre>
<p><strong>Error message</strong></p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
</code></pre>
| 1,039 | 2009-06-04T20:30:05Z | 952,954 | <p>Why do you use extend?</p>
<pre><code>reduce(lambda x, y: x+y, l)
</code></pre>
<p>This should work fine.</p>
| 18 | 2009-06-04T20:38:08Z | [
"python",
"list"
] |
Making a flat list out of list of lists in Python | 952,914 | <p>I wonder whether there is a shortcut to make a simple list out of list of lists in Python.</p>
<p>I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with <em>reduce</em>, but I get an error.</p>
<p><strong>Code</strong></p>
<pre><code>l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
</code></pre>
<p><strong>Error message</strong></p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
</code></pre>
| 1,039 | 2009-06-04T20:30:05Z | 952,993 | <p><strong>I take my statement back. sum is not the winner. Although it is faster when the list is small. But the performance degrades significantly with larger lists.</strong> </p>
<pre><code>>>> timeit.Timer(
'[item for sublist in l for item in sublist]',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]] * 10000'
).timeit(100)
2.0440959930419922
</code></pre>
<p>The sum version is still running for more than a minute and it hasn't done processing yet!</p>
<p>For medium lists:</p>
<pre><code>>>> timeit.Timer(
'[item for sublist in l for item in sublist]',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]] * 10'
).timeit()
20.126545906066895
>>> timeit.Timer(
'reduce(lambda x,y: x+y,l)',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]] * 10'
).timeit()
22.242258071899414
>>> timeit.Timer(
'sum(l, [])',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]] * 10'
).timeit()
16.449732065200806
</code></pre>
<p>Using small lists and timeit: number=1000000</p>
<pre><code>>>> timeit.Timer(
'[item for sublist in l for item in sublist]',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]]'
).timeit()
2.4598159790039062
>>> timeit.Timer(
'reduce(lambda x,y: x+y,l)',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]]'
).timeit()
1.5289170742034912
>>> timeit.Timer(
'sum(l, [])',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]]'
).timeit()
1.0598428249359131
</code></pre>
| 21 | 2009-06-04T20:46:49Z | [
"python",
"list"
] |
Making a flat list out of list of lists in Python | 952,914 | <p>I wonder whether there is a shortcut to make a simple list out of list of lists in Python.</p>
<p>I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with <em>reduce</em>, but I get an error.</p>
<p><strong>Code</strong></p>
<pre><code>l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
</code></pre>
<p><strong>Error message</strong></p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
</code></pre>
| 1,039 | 2009-06-04T20:30:05Z | 952,997 | <p>The reason your function didn't work: the extend extends array in-place and doesn't return it. You can still return x from lambda, using some trick:</p>
<pre><code>reduce(lambda x,y: x.extend(y) or x, l)
</code></pre>
<p>Note: extend is more efficient than + on lists.</p>
| 9 | 2009-06-04T20:47:13Z | [
"python",
"list"
] |
Making a flat list out of list of lists in Python | 952,914 | <p>I wonder whether there is a shortcut to make a simple list out of list of lists in Python.</p>
<p>I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with <em>reduce</em>, but I get an error.</p>
<p><strong>Code</strong></p>
<pre><code>l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
</code></pre>
<p><strong>Error message</strong></p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
</code></pre>
| 1,039 | 2009-06-04T20:30:05Z | 953,050 | <p>@Nadia: You have to use much longer lists. Then you see the difference quite strikingly!
My results for <code>len(l) = 1600</code></p>
<pre><code>A took 14.323 ms
B took 13.437 ms
C took 1.135 ms
</code></pre>
<p>where:</p>
<pre><code>A = reduce(lambda x,y: x+y,l)
B = sum(l, [])
C = [item for sublist in l for item in sublist]
</code></pre>
| 57 | 2009-06-04T20:57:24Z | [
"python",
"list"
] |
Making a flat list out of list of lists in Python | 952,914 | <p>I wonder whether there is a shortcut to make a simple list out of list of lists in Python.</p>
<p>I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with <em>reduce</em>, but I get an error.</p>
<p><strong>Code</strong></p>
<pre><code>l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
</code></pre>
<p><strong>Error message</strong></p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
</code></pre>
| 1,039 | 2009-06-04T20:30:05Z | 953,097 | <p>You can use <a href="http://docs.python.org/2/library/itertools.html#itertools.chain"><code>itertools.chain()</code></a>:</p>
<pre><code>>>> import itertools
>>> list2d = [[1,2,3],[4,5,6], [7], [8,9]]
>>> merged = list(itertools.chain(*list2d))
</code></pre>
<p>or, on Python >=2.6, use <a href="http://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable"><code>itertools.chain.from_iterable()</code></a> which doesn't require unpacking the list:</p>
<pre><code>>>> import itertools
>>> list2d = [[1,2,3],[4,5,6], [7], [8,9]]
>>> merged = list(itertools.chain.from_iterable(list2d))
</code></pre>
<p>This approach is arguably more readable than <code>[item for sublist in l for item in sublist]</code> and appears to be faster too:</p>
<pre><code>[me@home]$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99;import itertools' 'list(itertools.chain.from_iterable(l))'
10000 loops, best of 3: 24.2 usec per loop
[me@home]$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'
10000 loops, best of 3: 45.2 usec per loop
[me@home]$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'
1000 loops, best of 3: 488 usec per loop
[me@home]$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)'
1000 loops, best of 3: 522 usec per loop
[me@home]$ python --version
Python 2.7.3
</code></pre>
| 687 | 2009-06-04T21:06:17Z | [
"python",
"list"
] |
Making a flat list out of list of lists in Python | 952,914 | <p>I wonder whether there is a shortcut to make a simple list out of list of lists in Python.</p>
<p>I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with <em>reduce</em>, but I get an error.</p>
<p><strong>Code</strong></p>
<pre><code>l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
</code></pre>
<p><strong>Error message</strong></p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
</code></pre>
| 1,039 | 2009-06-04T20:30:05Z | 38,421,470 | <p>One can also use NumPy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.html" rel="nofollow">flat</a>:</p>
<pre><code>import numpy as np
list(np.array(l).flat)
</code></pre>
| 4 | 2016-07-17T12:57:48Z | [
"python",
"list"
] |
Making a flat list out of list of lists in Python | 952,914 | <p>I wonder whether there is a shortcut to make a simple list out of list of lists in Python.</p>
<p>I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with <em>reduce</em>, but I get an error.</p>
<p><strong>Code</strong></p>
<pre><code>l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
</code></pre>
<p><strong>Error message</strong></p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
</code></pre>
| 1,039 | 2009-06-04T20:30:05Z | 39,493,960 | <p>There seems to be a confusion with <code>operator.add</code>! When you add two lists together, the correct term for that is <code>concat</code>, not add. <code>operator.concat</code> is what you need to use.</p>
<p>If you're thinking functional, it is as easy as this::</p>
<pre><code>>>> list2d = ((1,2,3),(4,5,6), (7,), (8,9))
>>> reduce(operator.concat, list2d)
(1, 2, 3, 4, 5, 6, 7, 8, 9)
</code></pre>
<p>You see reduce respects the sequence type, so when you supply a tuple, you get back a tuple. let's try with a list::</p>
<pre><code>>>> list2d = [[1,2,3],[4,5,6], [7], [8,9]]
>>> reduce(operator.concat, list2d)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>Aha, you get back a list.</p>
<p>How about performance::</p>
<pre><code>>>> list2d = [[1,2,3],[4,5,6], [7], [8,9]]
>>> %timeit list(itertools.chain.from_iterable(list2d))
1000000 loops, best of 3: 1.36 µs per loop
</code></pre>
<p>from_iterable is pretty fast! But it's no comparison to reduce with concat.</p>
<pre><code>>>> list2d = ((1,2,3),(4,5,6), (7,), (8,9))
>>> %timeit reduce(operator.concat, list2d)
1000000 loops, best of 3: 492 ns per loop
</code></pre>
| 3 | 2016-09-14T15:09:16Z | [
"python",
"list"
] |
Making a flat list out of list of lists in Python | 952,914 | <p>I wonder whether there is a shortcut to make a simple list out of list of lists in Python.</p>
<p>I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with <em>reduce</em>, but I get an error.</p>
<p><strong>Code</strong></p>
<pre><code>l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
</code></pre>
<p><strong>Error message</strong></p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
</code></pre>
| 1,039 | 2009-06-04T20:30:05Z | 39,987,478 | <p>What about this one-liner:</p>
<pre class="lang-python prettyprint-override"><code>[k for k in str(a) if k.isdigit()]
</code></pre>
<p>It will work no matter how many levels of depth (Although only for one digit numbers)</p>
| 0 | 2016-10-11T22:01:23Z | [
"python",
"list"
] |
Explicit access to Python's built in scope | 953,027 | <p>How do you explicitly access name in Python's built in scope? </p>
<p>One situation where I ran in to this was a in module, say called foo, which happened to have an open function. In another module foo's open function would be accessible as foo.open which works well. In foo itself though, open blocks the built in open. How can you access the built in version of a name like open explicitly?</p>
<p>I am aware it is probably practically bad idea to block any built in name, but I am still curious to know if there is a way to explicitly access the built in scope.</p>
| 10 | 2009-06-04T20:54:02Z | 953,044 | <p>It's something like</p>
<pre><code>__builtins__.open()
</code></pre>
| -2 | 2009-06-04T20:56:22Z | [
"python"
] |
Explicit access to Python's built in scope | 953,027 | <p>How do you explicitly access name in Python's built in scope? </p>
<p>One situation where I ran in to this was a in module, say called foo, which happened to have an open function. In another module foo's open function would be accessible as foo.open which works well. In foo itself though, open blocks the built in open. How can you access the built in version of a name like open explicitly?</p>
<p>I am aware it is probably practically bad idea to block any built in name, but I am still curious to know if there is a way to explicitly access the built in scope.</p>
| 10 | 2009-06-04T20:54:02Z | 953,063 | <p>Use <code>__builtin__</code>.</p>
<pre><code>def open():
pass
import __builtin__
print open
print __builtin__.open
</code></pre>
<p>... gives you ...</p>
<blockquote>
<p><code><function open at 0x011E8670></code><br />
<code><built-in function open></code> </p>
</blockquote>
| 11 | 2009-06-04T21:00:00Z | [
"python"
] |
Why won't python allow me to delete files? | 953,040 | <p>I've created a python script that gets a list of files from a text file and deletes them if they're empty. It correctly detects empty files but it doesn't want to delete them. It gives me:</p>
<pre><code>(32, 'The process cannot access the file because it is being used by another process')
</code></pre>
<p>I've used two different tools to check whether the files are locked or not and I'm certain that they are not. I used sysinternals process explorer and LockHunter. Furthermore, I'm able to just manually delete the files myself. I obviously don't want to do that for all of them as there are hundreds in various locations.</p>
<p>The script:</p>
<pre><code>import os.path
import sys
def DeleteFilesFromListIfBlank(PathToListOfFiles):
ListOfFiles = open(PathToListOfFiles)
FilesToCheck = [];
for line in ListOfFiles.readlines():
if(len(line) > 1):
line = line.rstrip();
FilesToCheck.append(line)
print "Found %s files to check. Starting check." % len(FilesToCheck)
FilesToRemove = [];
for line in FilesToCheck:
#print "Opening %s" % line
try:
ActiveFile = open(line);
Length = len(ActiveFile.read())
if(Length < 691 and ActiveFile.read() == ""):
print "Deleting %s" % line
os.unlink(line);
else:
print "Keeping %s" % line
except IOError,message:
print "Could not open file: $s" % message
except Exception as inst:
print inst.args
DeleteFilesFromListIfBlank("C:\\ListOfResx.txt")
</code></pre>
<p>I've tried using both os.unlink and os.remove. I'm running Python 2.6 on Vista64</p>
<p>Thanks</p>
| 3 | 2009-06-04T20:55:38Z | 953,052 | <p>You need to call <code>.close()</code> on the file object before you try and delete it.</p>
<p>Edit: And really you shouldn't be opening the file at all. <code>os.stat()</code> will tell you the size of a file (and 9 other values) without ever opening the file.</p>
<p>This (I think) does the same thing but is a little cleaner (IMHO):</p>
<pre><code>import os
_MAX_SIZE = 691
def delete_if_blank(listFile):
# Make a list of files to check.
with open(listFile) as listFile:
filesToCheck = filter(None, (line.rstrip() for line in listFile.readlines()))
# listFile is automatically closed now because we're out of the 'with' statement.
print "Found %u files to check. Starting check." % len(filesToCheck)
# Remove each file.
for filename in filesToCheck:
if os.stat(filename).st_size < _MAX_SIZE:
print "Deleting %s" % filename
os.remove(filename)
else:
print "Keeping %s" % filename
</code></pre>
| 14 | 2009-06-04T20:57:40Z | [
"python",
"file-io"
] |
Why won't python allow me to delete files? | 953,040 | <p>I've created a python script that gets a list of files from a text file and deletes them if they're empty. It correctly detects empty files but it doesn't want to delete them. It gives me:</p>
<pre><code>(32, 'The process cannot access the file because it is being used by another process')
</code></pre>
<p>I've used two different tools to check whether the files are locked or not and I'm certain that they are not. I used sysinternals process explorer and LockHunter. Furthermore, I'm able to just manually delete the files myself. I obviously don't want to do that for all of them as there are hundreds in various locations.</p>
<p>The script:</p>
<pre><code>import os.path
import sys
def DeleteFilesFromListIfBlank(PathToListOfFiles):
ListOfFiles = open(PathToListOfFiles)
FilesToCheck = [];
for line in ListOfFiles.readlines():
if(len(line) > 1):
line = line.rstrip();
FilesToCheck.append(line)
print "Found %s files to check. Starting check." % len(FilesToCheck)
FilesToRemove = [];
for line in FilesToCheck:
#print "Opening %s" % line
try:
ActiveFile = open(line);
Length = len(ActiveFile.read())
if(Length < 691 and ActiveFile.read() == ""):
print "Deleting %s" % line
os.unlink(line);
else:
print "Keeping %s" % line
except IOError,message:
print "Could not open file: $s" % message
except Exception as inst:
print inst.args
DeleteFilesFromListIfBlank("C:\\ListOfResx.txt")
</code></pre>
<p>I've tried using both os.unlink and os.remove. I'm running Python 2.6 on Vista64</p>
<p>Thanks</p>
| 3 | 2009-06-04T20:55:38Z | 953,054 | <p>Are you opening each file and then trying to delete it? If so, try closing it first.</p>
| 4 | 2009-06-04T20:58:09Z | [
"python",
"file-io"
] |
Why won't python allow me to delete files? | 953,040 | <p>I've created a python script that gets a list of files from a text file and deletes them if they're empty. It correctly detects empty files but it doesn't want to delete them. It gives me:</p>
<pre><code>(32, 'The process cannot access the file because it is being used by another process')
</code></pre>
<p>I've used two different tools to check whether the files are locked or not and I'm certain that they are not. I used sysinternals process explorer and LockHunter. Furthermore, I'm able to just manually delete the files myself. I obviously don't want to do that for all of them as there are hundreds in various locations.</p>
<p>The script:</p>
<pre><code>import os.path
import sys
def DeleteFilesFromListIfBlank(PathToListOfFiles):
ListOfFiles = open(PathToListOfFiles)
FilesToCheck = [];
for line in ListOfFiles.readlines():
if(len(line) > 1):
line = line.rstrip();
FilesToCheck.append(line)
print "Found %s files to check. Starting check." % len(FilesToCheck)
FilesToRemove = [];
for line in FilesToCheck:
#print "Opening %s" % line
try:
ActiveFile = open(line);
Length = len(ActiveFile.read())
if(Length < 691 and ActiveFile.read() == ""):
print "Deleting %s" % line
os.unlink(line);
else:
print "Keeping %s" % line
except IOError,message:
print "Could not open file: $s" % message
except Exception as inst:
print inst.args
DeleteFilesFromListIfBlank("C:\\ListOfResx.txt")
</code></pre>
<p>I've tried using both os.unlink and os.remove. I'm running Python 2.6 on Vista64</p>
<p>Thanks</p>
| 3 | 2009-06-04T20:55:38Z | 953,055 | <p>You probably need to close the filehandle <code>ActiveFile</code> before you try to delete it.</p>
| 3 | 2009-06-04T20:58:18Z | [
"python",
"file-io"
] |
Why won't python allow me to delete files? | 953,040 | <p>I've created a python script that gets a list of files from a text file and deletes them if they're empty. It correctly detects empty files but it doesn't want to delete them. It gives me:</p>
<pre><code>(32, 'The process cannot access the file because it is being used by another process')
</code></pre>
<p>I've used two different tools to check whether the files are locked or not and I'm certain that they are not. I used sysinternals process explorer and LockHunter. Furthermore, I'm able to just manually delete the files myself. I obviously don't want to do that for all of them as there are hundreds in various locations.</p>
<p>The script:</p>
<pre><code>import os.path
import sys
def DeleteFilesFromListIfBlank(PathToListOfFiles):
ListOfFiles = open(PathToListOfFiles)
FilesToCheck = [];
for line in ListOfFiles.readlines():
if(len(line) > 1):
line = line.rstrip();
FilesToCheck.append(line)
print "Found %s files to check. Starting check." % len(FilesToCheck)
FilesToRemove = [];
for line in FilesToCheck:
#print "Opening %s" % line
try:
ActiveFile = open(line);
Length = len(ActiveFile.read())
if(Length < 691 and ActiveFile.read() == ""):
print "Deleting %s" % line
os.unlink(line);
else:
print "Keeping %s" % line
except IOError,message:
print "Could not open file: $s" % message
except Exception as inst:
print inst.args
DeleteFilesFromListIfBlank("C:\\ListOfResx.txt")
</code></pre>
<p>I've tried using both os.unlink and os.remove. I'm running Python 2.6 on Vista64</p>
<p>Thanks</p>
| 3 | 2009-06-04T20:55:38Z | 953,056 | <p>It's <strong>you</strong> that has the file open - you need to close it before trying to delete it:</p>
<pre><code>ActiveFile = open(line);
Length = len(ActiveFile.read())
ActiveFile.close() # Insert this line!
</code></pre>
<p>or just get the filesize without opening the file:</p>
<pre><code>Length = os.path.getsize(line)
</code></pre>
| 6 | 2009-06-04T20:58:25Z | [
"python",
"file-io"
] |
Why won't python allow me to delete files? | 953,040 | <p>I've created a python script that gets a list of files from a text file and deletes them if they're empty. It correctly detects empty files but it doesn't want to delete them. It gives me:</p>
<pre><code>(32, 'The process cannot access the file because it is being used by another process')
</code></pre>
<p>I've used two different tools to check whether the files are locked or not and I'm certain that they are not. I used sysinternals process explorer and LockHunter. Furthermore, I'm able to just manually delete the files myself. I obviously don't want to do that for all of them as there are hundreds in various locations.</p>
<p>The script:</p>
<pre><code>import os.path
import sys
def DeleteFilesFromListIfBlank(PathToListOfFiles):
ListOfFiles = open(PathToListOfFiles)
FilesToCheck = [];
for line in ListOfFiles.readlines():
if(len(line) > 1):
line = line.rstrip();
FilesToCheck.append(line)
print "Found %s files to check. Starting check." % len(FilesToCheck)
FilesToRemove = [];
for line in FilesToCheck:
#print "Opening %s" % line
try:
ActiveFile = open(line);
Length = len(ActiveFile.read())
if(Length < 691 and ActiveFile.read() == ""):
print "Deleting %s" % line
os.unlink(line);
else:
print "Keeping %s" % line
except IOError,message:
print "Could not open file: $s" % message
except Exception as inst:
print inst.args
DeleteFilesFromListIfBlank("C:\\ListOfResx.txt")
</code></pre>
<p>I've tried using both os.unlink and os.remove. I'm running Python 2.6 on Vista64</p>
<p>Thanks</p>
| 3 | 2009-06-04T20:55:38Z | 953,062 | <p>Try ActiveFile.close() before doing the unlink.</p>
<p>Also, reading the whole file isn't necessary, you can use os.path.getsize(filename) == 0.</p>
| 9 | 2009-06-04T20:59:35Z | [
"python",
"file-io"
] |
SSH Connection with Python 3.0 | 953,477 | <p>How can I make an SSH connection in Python 3.0? I want to save a file on a remote computer where I have password-less SSH set up.</p>
| 6 | 2009-06-04T22:39:35Z | 953,509 | <p>It might take a little work because "<a href="http://twistedmatrix.com/projects/conch/documentation/howto/conch%5Fclient.html" rel="nofollow">twisted:conch</a>" does not appear to have a 3.0 variant.</p>
| 0 | 2009-06-04T22:46:57Z | [
"python",
"file",
"ssh"
] |
SSH Connection with Python 3.0 | 953,477 | <p>How can I make an SSH connection in Python 3.0? I want to save a file on a remote computer where I have password-less SSH set up.</p>
| 6 | 2009-06-04T22:39:35Z | 953,510 | <p>I recommend calling ssh as a subprocess. It's reliable and portable.</p>
<pre><code>import subprocess
proc = subprocess.Popen(['ssh', 'user@host', 'cat > %s' % filename],
stdin=subprocess.PIPE)
proc.communicate(file_contents)
if proc.retcode != 0:
...
</code></pre>
<p>You'd have to worry about quoting the destination filename. If you want more flexibility, you could even do this:</p>
<pre><code>import subprocess
import tarfile
import io
tardata = io.BytesIO()
tar = tarfile.open(mode='w:gz', fileobj=tardata)
... put stuff in tar ...
proc = subprocess.Popen(['ssh', 'user@host', 'tar xz'],
stdin=subprocess.PIPE)
proc.communicate(tardata.getvalue())
if proc.retcode != 0:
...
</code></pre>
| 11 | 2009-06-04T22:47:36Z | [
"python",
"file",
"ssh"
] |
SSH Connection with Python 3.0 | 953,477 | <p>How can I make an SSH connection in Python 3.0? I want to save a file on a remote computer where I have password-less SSH set up.</p>
| 6 | 2009-06-04T22:39:35Z | 953,533 | <p>You want all of the ssh-functionality implemented as a python library? Have a look at paramiko, although I think it's not ported to Python 3.0 (yet?).</p>
<p>If you can use an existing ssh installation you can use the <code>subprocess</code> way Dietrich described, or (another way) you could also use <code>pexcept</code> (<a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">website here</a>).</p>
| 1 | 2009-06-04T22:55:15Z | [
"python",
"file",
"ssh"
] |
SSH Connection with Python 3.0 | 953,477 | <p>How can I make an SSH connection in Python 3.0? I want to save a file on a remote computer where I have password-less SSH set up.</p>
| 6 | 2009-06-04T22:39:35Z | 5,141,491 | <p>I have written <a href="http://www.no-ack.org/2010/11/python-bindings-for-libssh2.html" rel="nofollow">Python bindings for libssh2</a>, that run on Python 2.4, 2.5, 2.6, 2.7 and <strong>3</strong>.</p>
| 0 | 2011-02-28T11:42:11Z | [
"python",
"file",
"ssh"
] |
SSH Connection with Python 3.0 | 953,477 | <p>How can I make an SSH connection in Python 3.0? I want to save a file on a remote computer where I have password-less SSH set up.</p>
| 6 | 2009-06-04T22:39:35Z | 16,390,822 | <p><a href="https://github.com/wallunit/ssh4py" rel="nofollow">libssh2</a> works great for Python 3.x.<br>
See this Stack Overflow article
<a href="http://stackoverflow.com/questions/14367020/how-to-send-a-file-using-scp-using-python-3-2">How to send a file using scp using python 3.2?</a></p>
| 0 | 2013-05-06T01:21:44Z | [
"python",
"file",
"ssh"
] |
SSH Connection with Python 3.0 | 953,477 | <p>How can I make an SSH connection in Python 3.0? I want to save a file on a remote computer where I have password-less SSH set up.</p>
| 6 | 2009-06-04T22:39:35Z | 18,154,637 | <p>First:</p>
<p>Two steps to login via ssh without password</p>
<p>in your terminal</p>
<pre><code>[macm@macm ~]$ ssh-keygen
[macm@macm ~]$ ssh-copy-id -i $HOME/.ssh/id_rsa.pub root@192.168.1.XX <== change
</code></pre>
<p>Now with python</p>
<pre><code>from subprocess import PIPE, Popen
cmd = 'uname -a'
stream = Popen(['ssh', 'root@192.168.1.XX', cmd],
stdin=PIPE, stdout=PIPE)
rsp = stream.stdout.read().decode('utf-8')
print(rsp)
</code></pre>
| 1 | 2013-08-09T19:55:19Z | [
"python",
"file",
"ssh"
] |
Check unread count of Gmail messages with Python | 953,561 | <p>How can I check the number of unread Gmail message in my inbox with a short Python script? Bonus points for retrieving the password from a file.</p>
| 31 | 2009-06-04T23:05:30Z | 953,581 | <p>Well it isn't a code snippet but I imagine using <a href="http://docs.python.org/library/imaplib.html">imaplib</a> and the <a href="http://mail.google.com/support/bin/answer.py?hl=en&answer=75725">Gmail IMAP instructions</a> get you most of the way there.</p>
| 6 | 2009-06-04T23:12:08Z | [
"python",
"email",
"gmail",
"pop3"
] |
Check unread count of Gmail messages with Python | 953,561 | <p>How can I check the number of unread Gmail message in my inbox with a short Python script? Bonus points for retrieving the password from a file.</p>
| 31 | 2009-06-04T23:05:30Z | 953,583 | <p>Use <a href="http://www.holovaty.com/writing/278/" rel="nofollow">Gmail.py</a></p>
<pre><code>file = open("filename","r")
usr = file.readline()
pwd = file.readline()
gmail = GmailClient()
gmail.login(usr, pwd)
unreadMail = gmail.get_inbox_conversations(is_unread=True)
print unreadMail
</code></pre>
<p>Gets login information from a text file assuming the login name and password are on separate lines.</p>
| -1 | 2009-06-04T23:12:21Z | [
"python",
"email",
"gmail",
"pop3"
] |
Check unread count of Gmail messages with Python | 953,561 | <p>How can I check the number of unread Gmail message in my inbox with a short Python script? Bonus points for retrieving the password from a file.</p>
| 31 | 2009-06-04T23:05:30Z | 953,607 | <p>I advise you to use <a href="https://developers.google.com/gmail/gmail_inbox_feed" rel="nofollow">Gmail atom feed</a></p>
<p>It is as simple as this:</p>
<pre><code>import urllib
url = 'https://mail.google.com/mail/feed/atom/'
opener = urllib.FancyURLopener()
f = opener.open(url)
feed = f.read()
</code></pre>
<p>You can then use the feed parse function in this nice article: <a href="http://g33k.wordpress.com/2006/07/31/check-gmail-the-python-way/" rel="nofollow">Check Gmail the pythonic way</a></p>
| 22 | 2009-06-04T23:22:58Z | [
"python",
"email",
"gmail",
"pop3"
] |
Check unread count of Gmail messages with Python | 953,561 | <p>How can I check the number of unread Gmail message in my inbox with a short Python script? Bonus points for retrieving the password from a file.</p>
| 31 | 2009-06-04T23:05:30Z | 953,617 | <p>Once you are logged in (do this manually or with gmail.py) you should use the feed.</p>
<p>It is located here:
<a href="http://mail.google.com/mail/feed/atom" rel="nofollow">http://mail.google.com/mail/feed/atom</a></p>
<p>It is the way Google does it. Here is a link to their js chrome extension:
<a href="http://dev.chromium.org/developers/design-documents/extensions/samples/gmail.zip" rel="nofollow">http://dev.chromium.org/developers/design-documents/extensions/samples/gmail.zip</a></p>
<p>You will then be able to parse xml that looks like this:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
<title>Gmail - Inbox for yourmail@gmail.com</title>
<tagline>New messages in your Gmail Inbox</tagline>
<fullcount>142</fullcount>
</code></pre>
| 1 | 2009-06-04T23:30:34Z | [
"python",
"email",
"gmail",
"pop3"
] |
Check unread count of Gmail messages with Python | 953,561 | <p>How can I check the number of unread Gmail message in my inbox with a short Python script? Bonus points for retrieving the password from a file.</p>
| 31 | 2009-06-04T23:05:30Z | 954,099 | <p>Well, I'm going to go ahead and spell out an imaplib solution as Cletus suggested. I don't see why people feel the need to use gmail.py or Atom for this. This kind of thing is what IMAP was designed for. Gmail.py is particularly egregious as it actually parses Gmail's HTML. That may be necessary for some things, but not to get a message count!</p>
<pre><code>import imaplib, re
conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
conn.login(username, password)
unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1)
</code></pre>
<p>Pre-compiling the regex may improve performance slightly.</p>
| 22 | 2009-06-05T03:05:12Z | [
"python",
"email",
"gmail",
"pop3"
] |
Check unread count of Gmail messages with Python | 953,561 | <p>How can I check the number of unread Gmail message in my inbox with a short Python script? Bonus points for retrieving the password from a file.</p>
| 31 | 2009-06-04T23:05:30Z | 3,984,850 | <pre><code>import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com','993')
obj.login('username','password')
obj.select()
obj.search(None,'UnSeen')
</code></pre>
| 49 | 2010-10-21T06:30:45Z | [
"python",
"email",
"gmail",
"pop3"
] |
Check unread count of Gmail messages with Python | 953,561 | <p>How can I check the number of unread Gmail message in my inbox with a short Python script? Bonus points for retrieving the password from a file.</p>
| 31 | 2009-06-04T23:05:30Z | 7,761,930 | <p>For a complete implementation of reading the value from the atom feed:</p>
<pre><code>import urllib2
import base64
from xml.dom.minidom import parse
def gmail_unread_count(user, password):
"""
Takes a Gmail user name and password and returns the unread
messages count as an integer.
"""
# Build the authentication string
b64auth = base64.encodestring("%s:%s" % (user, password))
auth = "Basic " + b64auth
# Build the request
req = urllib2.Request("https://mail.google.com/mail/feed/atom/")
req.add_header("Authorization", auth)
handle = urllib2.urlopen(req)
# Build an XML dom tree of the feed
dom = parse(handle)
handle.close()
# Get the "fullcount" xml object
count_obj = dom.getElementsByTagName("fullcount")[0]
# get its text and convert it to an integer
return int(count_obj.firstChild.wholeText)
</code></pre>
| 5 | 2011-10-14T00:28:22Z | [
"python",
"email",
"gmail",
"pop3"
] |
Which gps library would you recommend for python? | 953,701 | <p>I'm looking for a free library for python that can calculate your direction and your speed from GPS coordinates and maybe can calculate if you are in some boundaries or things like this. </p>
<p>Are there Libraries that you know and that worked well for you?</p>
<p><strong>Edit:</strong> Ok it seems I have to specify this a little bit. We are using python on a linux machine and getting the data from the gpsd. So I hope there is no need for a speciel library for only talking to the device. What I'm looking for is python code doing some basic calculations with the data. Such as comparing the last positions and calculate speed and direction.</p>
| 8 | 2009-06-05T00:01:57Z | 954,101 | <p>I'm not sure I understand your exact requirements, but, depending on your device &c, there seem to be many possible candidates, such as:</p>
<ul>
<li><a href="http://gagravarr.org/code/" rel="nofollow">S60 GPS Info Viewer</a></li>
<li><a href="https://github.com/quentinsf/pygarmin" rel="nofollow">pygarmin</a></li>
<li><a href="http://linux.softpedia.com/get/Utilities/pygps-6071.shtml" rel="nofollow">pygps</a> (mirror)</li>
</ul>
<p>If what you mean is that you've already obtained the GPS' unit output and just need to parse it &c, I suspect that one or more of the above examples (which unfortunately I have not tried) will contain well-isolated modules for that task, which, depending on licensing conditions, you could repurpose; <a href="http://stackoverflow.com/questions/311763/parsing-gps-receiver-output-via-regex-in-python">this SO question</a> might also help if that's what you're doing.</p>
| 4 | 2009-06-05T03:06:55Z | [
"python",
"gps",
"gpsd"
] |
Which gps library would you recommend for python? | 953,701 | <p>I'm looking for a free library for python that can calculate your direction and your speed from GPS coordinates and maybe can calculate if you are in some boundaries or things like this. </p>
<p>Are there Libraries that you know and that worked well for you?</p>
<p><strong>Edit:</strong> Ok it seems I have to specify this a little bit. We are using python on a linux machine and getting the data from the gpsd. So I hope there is no need for a speciel library for only talking to the device. What I'm looking for is python code doing some basic calculations with the data. Such as comparing the last positions and calculate speed and direction.</p>
| 8 | 2009-06-05T00:01:57Z | 954,729 | <p>The book "Beginning Python Visualization" includes just such an example - parsing GPS data and inferring speed and location from it. Its source code is available online at <a href="http://www.apress.com/" rel="nofollow">http://www.apress.com/</a></p>
| 3 | 2009-06-05T07:53:42Z | [
"python",
"gps",
"gpsd"
] |
Which gps library would you recommend for python? | 953,701 | <p>I'm looking for a free library for python that can calculate your direction and your speed from GPS coordinates and maybe can calculate if you are in some boundaries or things like this. </p>
<p>Are there Libraries that you know and that worked well for you?</p>
<p><strong>Edit:</strong> Ok it seems I have to specify this a little bit. We are using python on a linux machine and getting the data from the gpsd. So I hope there is no need for a speciel library for only talking to the device. What I'm looking for is python code doing some basic calculations with the data. Such as comparing the last positions and calculate speed and direction.</p>
| 8 | 2009-06-05T00:01:57Z | 954,883 | <p>The GPS sentences that you receive from a GPS device are pretty easy to decode, and this looks like a fun project. I'm not sure what you get from gspd, but if it's these sentences, I actually had to do something like this for school a few weeks ago (but in LabView):</p>
<pre><code>$GPGGA,hhmmss.ss,llll.ll,a,yyyyy.yy,a,x,xx,x.x,x.x,M,x.x,M,x.x,xxxx
hhmmss.ss = UTC of position
llll.ll = latitude of position
a = N or S
yyyyy.yy = Longitude of position
a = E or W
x = GPS Quality indicator (0=no fix, 1=GPS fix, 2=Dif. GPS fix)
xx = number of satellites in use
x.x = horizontal dilution of precision
x.x = Antenna altitude above mean-sea-level
M = units of antenna altitude, meters
x.x = Geoidal separation
M = units of geoidal separation, meters
x.x = Age of Differential GPS data (seconds)
xxxx = Differential reference station ID
</code></pre>
<p>So you could just do a gpsstring.split(',') and you'll get an array of all elements which you can then parse. To see more about these sentences (there are others I think for speed and direction), click <a href="http://aprs.gids.nl/nmea/" rel="nofollow">here</a>.</p>
<p>For example, to get the approximate distance between two points you can use the <a href="http://en.wikipedia.org/wiki/Haversine%5Fformula" rel="nofollow">Haversine Formula</a>:</p>
<pre><code>distance=R*2*asin(sqrt((sin((lat1-lat2)/2))**2
+cos(lat1)*cos(lat2)*(sin((long1-long2)/2))**2))
</code></pre>
<p>Where R is the radius of the Earth in the unit of measurement you want to get your result in (for example R=6372km). That actual line is taken from the LabView program I had lying around, but the syntax is pretty similar to Python's (maybe check the <a href="http://www.ferg.org/projects/python%5Fgotchas.html#contents%5Fitem%5F3" rel="nofollow">division</a> operator, you might want to do "from <strong>future</strong> import division".</p>
<p>Also, lat1, lat2, long1 and long2 have to be expressed in radians. The format you're getting them in is pretty strange (hhmm.ff, where ff are fractions of minutes, so they go from 0 to 99 instead of 0 to 59 (as seconds)).</p>
<p>The code I used for that is:</p>
<pre><code>h=floor(x/100);
m=floor(x-(h*100));
s=(x-floor(x))*60;
deg=sgn*(h+(m/60)+(s/3600));
rad=deg*pi/180;
</code></pre>
<p>Where sign is 1 for North and East, and -1 for South and East. Again, watch out for division.</p>
<p>Checking boundaries is I think the easiest part. If you've already got the positions in radians or degrees, you can just check if latitude is between two lat boundaries, and do the same for longitude.</p>
<p>Write a wrapper around everything, and you've got your GPS library :)</p>
| 2 | 2009-06-05T08:48:47Z | [
"python",
"gps",
"gpsd"
] |
Which gps library would you recommend for python? | 953,701 | <p>I'm looking for a free library for python that can calculate your direction and your speed from GPS coordinates and maybe can calculate if you are in some boundaries or things like this. </p>
<p>Are there Libraries that you know and that worked well for you?</p>
<p><strong>Edit:</strong> Ok it seems I have to specify this a little bit. We are using python on a linux machine and getting the data from the gpsd. So I hope there is no need for a speciel library for only talking to the device. What I'm looking for is python code doing some basic calculations with the data. Such as comparing the last positions and calculate speed and direction.</p>
| 8 | 2009-06-05T00:01:57Z | 973,022 | <p>Apparently the python module that comes with gpsd is the best module to go with for us.
For a start look <a href="http://www.perrygeo.net/wordpress/?p=13">here</a></p>
<p>The gps module coming with the gpsd has some very useful functions. The first one is getting the data from gpsd and transforming those data in a usable data structure.
Then the moduls give you access to your speed, and your current heading relative to north.
Also included is a function for calculating the distance between two coordinates on the earth taking the spherical nature of earth into account. </p>
<p>The functions that are missing for our special case are: </p>
<p>Calculating the heading between to points. Means I am at point a facing north to which degree do I have to turn to face the point I want to navigate to. </p>
<p>Taking the data of the first function and our current heading to calculate a turn in degrees that we have to do to face a desired point (not a big deal because it is mostly only a subtraction)</p>
<p>The biggest problem for working with this library is that it is mostly a wrapper for the gpsd so if you are programming on a different OS then you gpscode should work on like Windows or MacOS you are not able to run the code or to install the module.</p>
| 8 | 2009-06-09T23:31:28Z | [
"python",
"gps",
"gpsd"
] |
Which gps library would you recommend for python? | 953,701 | <p>I'm looking for a free library for python that can calculate your direction and your speed from GPS coordinates and maybe can calculate if you are in some boundaries or things like this. </p>
<p>Are there Libraries that you know and that worked well for you?</p>
<p><strong>Edit:</strong> Ok it seems I have to specify this a little bit. We are using python on a linux machine and getting the data from the gpsd. So I hope there is no need for a speciel library for only talking to the device. What I'm looking for is python code doing some basic calculations with the data. Such as comparing the last positions and calculate speed and direction.</p>
| 8 | 2009-06-05T00:01:57Z | 33,309,901 | <p>Most good GPS units (we use Oncore M12M) will actually give you, as output, your velocity and heading. I would first check your GPS receiver's documentation to see if this information is already being sent, or if such a message can be enabled. In my experience, this data is usually part of the standard telemetry a receiver will give you. </p>
<p>If that doesn't work, I think your best bet is using the details of WGS-84 (the GPS coordinate system) to obtain an actual (x,y,z) coordinate and then difference it with the next one to find your heading and take the magnitude of the difference over the time interval to find your velocity. Some details here:
<a href="http://topex.ucsd.edu/geodynamics/14gravity1_2.pdf" rel="nofollow">http://topex.ucsd.edu/geodynamics/14gravity1_2.pdf</a></p>
<p>If you really want a package that does all this, I think pyEphem is pretty good, although I think you might save a little time searching and gain some good knowledge by writing it yourself.</p>
<p>(Sorry if unhelpful, first time poster, still learning how to stack overflow)</p>
| 1 | 2015-10-23T19:18:53Z | [
"python",
"gps",
"gpsd"
] |
how to program functions with alternative return value signatures in python? (next() for alternative iterators) | 953,914 | <p>e.g. so that these would both work - is it possible?</p>
<pre><code>(val,VAL2) = func(args)
val = func(args)
</code></pre>
<p>Where <strong>val</strong> is <strong>not a tuple</strong></p>
<p>For example I'd like these to work for my custom object <strong>something</strong></p>
<pre><code>for item in something:
do_item(item) #where again item - is not a tuple
for (item,key) in something:
do_more(key,item)
</code></pre>
<p>I thought that I need to implement next() function in two different ways... </p>
<p><strong>edit:</strong> as follows from the answers below, this should not really be done.</p>
| 0 | 2009-06-05T01:42:41Z | 953,923 | <p>Have you tried that? It works.</p>
<pre><code>def myfunction(data):
datalen = len(data)
result1 = data[:datalen/2]
result2 = data[datalen/2:]
return result1, result2
a, b = myfunction('stuff')
print a
print b
c = myfunction('other stuff')
print c
</code></pre>
<p>In fact there is no such thing as "return signature". All functions return a single object. It seems that you are returning more than one, but in fact you wrap them into a container tuple object.</p>
| 4 | 2009-06-05T01:46:45Z | [
"python"
] |
how to program functions with alternative return value signatures in python? (next() for alternative iterators) | 953,914 | <p>e.g. so that these would both work - is it possible?</p>
<pre><code>(val,VAL2) = func(args)
val = func(args)
</code></pre>
<p>Where <strong>val</strong> is <strong>not a tuple</strong></p>
<p>For example I'd like these to work for my custom object <strong>something</strong></p>
<pre><code>for item in something:
do_item(item) #where again item - is not a tuple
for (item,key) in something:
do_more(key,item)
</code></pre>
<p>I thought that I need to implement next() function in two different ways... </p>
<p><strong>edit:</strong> as follows from the answers below, this should not really be done.</p>
| 0 | 2009-06-05T01:42:41Z | 953,926 | <p>It's possible only if you're happy for <code>val</code> to be a 2-item tuple (or if <code>args</code> need not be the same in the two cases). The former is what would happen if the function just ended with something like <code>return 23, 45</code>. Here's an example of the latter idea:</p>
<pre><code>def weirdfunc(how_many_returns):
assert 1 <= how_many_returns <= 4
return 'fee fie foo fum'.split()[:how_many_returns]
var1, var2 = weirdfunc(2) # var1 gets 'fee', var2 gets 'fie'
var, = weirdfunc(1) # var gets 'fee'
</code></pre>
| 1 | 2009-06-05T01:47:17Z | [
"python"
] |
how to program functions with alternative return value signatures in python? (next() for alternative iterators) | 953,914 | <p>e.g. so that these would both work - is it possible?</p>
<pre><code>(val,VAL2) = func(args)
val = func(args)
</code></pre>
<p>Where <strong>val</strong> is <strong>not a tuple</strong></p>
<p>For example I'd like these to work for my custom object <strong>something</strong></p>
<pre><code>for item in something:
do_item(item) #where again item - is not a tuple
for (item,key) in something:
do_more(key,item)
</code></pre>
<p>I thought that I need to implement next() function in two different ways... </p>
<p><strong>edit:</strong> as follows from the answers below, this should not really be done.</p>
| 0 | 2009-06-05T01:42:41Z | 953,933 | <p>Update:</p>
<p>Given the example use case, I'd write different generators to handle the cases:</p>
<pre><code>class Something(object):
def __init__(self):
self.d = {'a' : 1,
'b' : 2,
'c' : 3}
def items(self):
for i in self.d.values():
yield i
def items_keys(self):
for k,i in self.d.items():
yield i,k
something = Something()
for item in something.items():
....: print item
....:
1
3
2
for item,key in something.items_keys():
....: print key, " : ", item
....:
a : 1
b : 2
c : 3
</code></pre>
<p>Or</p>
<p>You can return a tuple:</p>
<pre><code>In [1]: def func(n):
...: return (n, n+1)
...:
In [2]: a,b = func(1)
In [3]: a
Out[3]: 1
In [4]: b
Out[4]: 2
In [5]: x = func(1)
In [6]: x
Out[6]: (1, 2)
</code></pre>
| 2 | 2009-06-05T01:48:38Z | [
"python"
] |
how to program functions with alternative return value signatures in python? (next() for alternative iterators) | 953,914 | <p>e.g. so that these would both work - is it possible?</p>
<pre><code>(val,VAL2) = func(args)
val = func(args)
</code></pre>
<p>Where <strong>val</strong> is <strong>not a tuple</strong></p>
<p>For example I'd like these to work for my custom object <strong>something</strong></p>
<pre><code>for item in something:
do_item(item) #where again item - is not a tuple
for (item,key) in something:
do_more(key,item)
</code></pre>
<p>I thought that I need to implement next() function in two different ways... </p>
<p><strong>edit:</strong> as follows from the answers below, this should not really be done.</p>
| 0 | 2009-06-05T01:42:41Z | 953,935 | <p>Yes, both would work. In the first example, val1 and val2 would have the two values. In the second example, val would have a tuple. You can try this in your python interpreter:</p>
<pre><code>>>> def foo():
... return ( 1, 2 )
...
>>> x = foo()
>>> (y,z) = foo()
>>> x
(1, 2)
>>> y
1
>>> z
2
</code></pre>
| 1 | 2009-06-05T01:49:17Z | [
"python"
] |
how to program functions with alternative return value signatures in python? (next() for alternative iterators) | 953,914 | <p>e.g. so that these would both work - is it possible?</p>
<pre><code>(val,VAL2) = func(args)
val = func(args)
</code></pre>
<p>Where <strong>val</strong> is <strong>not a tuple</strong></p>
<p>For example I'd like these to work for my custom object <strong>something</strong></p>
<pre><code>for item in something:
do_item(item) #where again item - is not a tuple
for (item,key) in something:
do_more(key,item)
</code></pre>
<p>I thought that I need to implement next() function in two different ways... </p>
<p><strong>edit:</strong> as follows from the answers below, this should not really be done.</p>
| 0 | 2009-06-05T01:42:41Z | 953,942 | <p>Yes it's doable:</p>
<pre><code>def a(b):
if b < 5:
return ("o", "k")
else:
return "ko"
</code></pre>
<p>and the result:</p>
<pre><code>>>> b = a(4)
>>> b
('o', 'k')
>>> b = a(6)
>>> b
'ko'
</code></pre>
<p>I think the thing after is to be careful when you will use the values returned...</p>
| 2 | 2009-06-05T01:50:38Z | [
"python"
] |
how to program functions with alternative return value signatures in python? (next() for alternative iterators) | 953,914 | <p>e.g. so that these would both work - is it possible?</p>
<pre><code>(val,VAL2) = func(args)
val = func(args)
</code></pre>
<p>Where <strong>val</strong> is <strong>not a tuple</strong></p>
<p>For example I'd like these to work for my custom object <strong>something</strong></p>
<pre><code>for item in something:
do_item(item) #where again item - is not a tuple
for (item,key) in something:
do_more(key,item)
</code></pre>
<p>I thought that I need to implement next() function in two different ways... </p>
<p><strong>edit:</strong> as follows from the answers below, this should not really be done.</p>
| 0 | 2009-06-05T01:42:41Z | 953,949 | <pre><code>>>> def func(a,b):
return (a,b)
>>> x = func(1,2)
>>> x
(1, 2)
>>> (y,z) = func(1,2)
>>> y
1
>>> z
2
</code></pre>
<p>That doesn't really answer your question. The real answer is that the left side of the assignment doesn't affect the returned type of the function and can't be used to distinguish between functions with different return types. As noted in other answers, the function can return different types from different return statements but it doesn't know what's on the other side of the equals sign. </p>
<p>In the case of this function, it returns a tuple. If you assign it to x, x has the value of the tuple. (y, z) on the left side of the assignment is "tuple unpacking". The tuple returned by func() is unpacked into y and z.</p>
| 2 | 2009-06-05T01:54:10Z | [
"python"
] |
how to program functions with alternative return value signatures in python? (next() for alternative iterators) | 953,914 | <p>e.g. so that these would both work - is it possible?</p>
<pre><code>(val,VAL2) = func(args)
val = func(args)
</code></pre>
<p>Where <strong>val</strong> is <strong>not a tuple</strong></p>
<p>For example I'd like these to work for my custom object <strong>something</strong></p>
<pre><code>for item in something:
do_item(item) #where again item - is not a tuple
for (item,key) in something:
do_more(key,item)
</code></pre>
<p>I thought that I need to implement next() function in two different ways... </p>
<p><strong>edit:</strong> as follows from the answers below, this should not really be done.</p>
| 0 | 2009-06-05T01:42:41Z | 954,202 | <p>This is asking for major confusion. Instead you can follow <code>dict</code> with separate keys, values, items, etc. methods, or you can use a convention of naming unused variables with a single underscore. Examples:</p>
<pre><code>for k in mydict.keys(): pass
for k, v in mydict.items(): pass
for a, b in myobj.foo(): pass
for a, _ in myobj.foo(): pass
for _, b in myobj.foo(): pass
for _, _, _, d in [("even", "multiple", "underscores", "works")]:
print(d)
for item in something: # or something.keys(), etc.
do_item(item)
for item, key in something.items():
do_more(key, item)
</code></pre>
<p>If this doesn't fit your function, you should refactor it as two or more functions, because it's clearly trying to fulfill two or more different goals.</p>
| 0 | 2009-06-05T03:48:57Z | [
"python"
] |
how to program functions with alternative return value signatures in python? (next() for alternative iterators) | 953,914 | <p>e.g. so that these would both work - is it possible?</p>
<pre><code>(val,VAL2) = func(args)
val = func(args)
</code></pre>
<p>Where <strong>val</strong> is <strong>not a tuple</strong></p>
<p>For example I'd like these to work for my custom object <strong>something</strong></p>
<pre><code>for item in something:
do_item(item) #where again item - is not a tuple
for (item,key) in something:
do_more(key,item)
</code></pre>
<p>I thought that I need to implement next() function in two different ways... </p>
<p><strong>edit:</strong> as follows from the answers below, this should not really be done.</p>
| 0 | 2009-06-05T01:42:41Z | 954,859 | <p>If you mean, can the function act differently based on the return types the caller is expecting, the answer is no (bar seriously nasty bytecode inspection). In this case, you should provide two different iterators on your object, and write something like:</p>
<pre><code>for item in something: # Default iterator: returns non-tuple objects
do_something(item)
for (item,key) in something.iter_pairs(): # iter_pairs returns different iterator
do_something_else(item, key)
</code></pre>
<p>eg. see the dictionary object, which uses this pattern. <code>for key in mydict</code> iterates over the dictionary keys. <code>for k,v in mydict.iteritems()</code> iterates over (key, value) pairs.</p>
<p><strong>[Edit]</strong> Just in case anyone wants to see what I mean by "seriously nasty bytecode inspection", here's a quick implementation:</p>
<pre><code>import inspect, opcode
def num_expected_results():
"""Return the number of items the caller is expecting in a tuple.
Returns None if a single value is expected, rather than a tuple.
"""
f = inspect.currentframe(2)
code = map(ord, f.f_code.co_code)
pos = f.f_lasti
if code[pos] == opcode.opmap['GET_ITER']: pos += 1 # Skip this and the FOR_ITER
if code[pos] > opcode.EXTENDED_ARG: pos +=5
elif code[pos] > opcode.HAVE_ARGUMENT: pos +=3
else: pos += 1
if code[pos] == opcode.opmap['UNPACK_SEQUENCE']:
return code[pos+1] + (code[pos+2] << 8)
return None
</code></pre>
<p>Usable something like:</p>
<pre><code>class MagicDict(dict):
def __iter__(self):
if num_expected_results() == 2:
for k,v in self.iteritems():
yield k,v
else:
for k in self.iterkeys():
yield k
d=MagicDict(foo=1, bar=2)
print "Keys:"
for key in d:
print " ", key
print "Values"
for k,v in d:
print " ",k,v
</code></pre>
<p><strong>Disclaimer:</strong> This is incredibly hacky, insanely bad practice, and <em>will</em> cause other programmers to hunt you down and kill you if they ever see it in real code. Only works on cpython (if that). <strong>Never</strong> use this in production code (or for that matter, probably any code).</p>
| 6 | 2009-06-05T08:40:32Z | [
"python"
] |
Error running tutorial that came along wxPython2.8 Docs and Demos | 954,132 | <p>I tried the following example code from the tutorial that came along "wxPython2.8 Docs and Demos" package.</p>
<pre><code>import wx
from frame import Frame
class App(wx.App):
"""Application class."""
def OnInit(self):
self.frame = Frame()
self.frame.Show()
self.SetTopWindow(self.frame)
return True
def main():
app = App()
app.MainLoop()
if __name__ == '__main__':
main()
</code></pre>
<p>but its giving me the following error</p>
<pre><code>Traceback (most recent call last):
File "C:/Documents and Settings/umair.ahmed/Desktop/wxpy.py", line 3, in <module>
from frame import Frame
ImportError: No module named frame
</code></pre>
<p>kindly help i am just a newbie with python </p>
| 1 | 2009-06-05T03:22:44Z | 954,147 | <p>I think you should skip the "from frame import Frame" and change:</p>
<pre><code>self.frame = Frame()
</code></pre>
<p>to:</p>
<pre><code>self.frame = wx.Frame()
</code></pre>
| 1 | 2009-06-05T03:28:03Z | [
"python",
"windows",
"wxpython"
] |
Error running tutorial that came along wxPython2.8 Docs and Demos | 954,132 | <p>I tried the following example code from the tutorial that came along "wxPython2.8 Docs and Demos" package.</p>
<pre><code>import wx
from frame import Frame
class App(wx.App):
"""Application class."""
def OnInit(self):
self.frame = Frame()
self.frame.Show()
self.SetTopWindow(self.frame)
return True
def main():
app = App()
app.MainLoop()
if __name__ == '__main__':
main()
</code></pre>
<p>but its giving me the following error</p>
<pre><code>Traceback (most recent call last):
File "C:/Documents and Settings/umair.ahmed/Desktop/wxpy.py", line 3, in <module>
from frame import Frame
ImportError: No module named frame
</code></pre>
<p>kindly help i am just a newbie with python </p>
| 1 | 2009-06-05T03:22:44Z | 954,163 | <p>Yeah, it's an ancient doc bug, see for example <a href="http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-02/4023.html" rel="nofollow">this 5-years-old post</a>:-(. Fix:</p>
<ul>
<li>delete the line that says <code>from frame
import Frame</code></li>
<li>change the line that says <code>self.frame
= Frame()</code> to say instead <code>self.frame = wx.Frame()</code></li>
</ul>
| 0 | 2009-06-05T03:33:54Z | [
"python",
"windows",
"wxpython"
] |
PyS60 application not going full screen | 954,272 | <p>I am very new to PyS60. I was testing how to set an application to full screen mode but unfortunately, it doesn't work as expected. I tested the script on Nokia 6120 Classic. Here is what I did:</p>
<p><code>
appuifw.app.screen = 'full'
</code></p>
<p>What I get is a half screen of my application with a plain white colour below. What am I doing wrong? Thanks in advance.</p>
| 3 | 2009-06-05T04:31:11Z | 955,340 | <p>If you haven't already, I would advise using the latest version of PyS60 from https://garage.maemo.org/frs/?group_id=854 and trying again.</p>
<p>Do the other two screen modes work as they are supposed to?</p>
| 0 | 2009-06-05T11:05:29Z | [
"python",
"symbian",
"pys60"
] |
PyS60 application not going full screen | 954,272 | <p>I am very new to PyS60. I was testing how to set an application to full screen mode but unfortunately, it doesn't work as expected. I tested the script on Nokia 6120 Classic. Here is what I did:</p>
<p><code>
appuifw.app.screen = 'full'
</code></p>
<p>What I get is a half screen of my application with a plain white colour below. What am I doing wrong? Thanks in advance.</p>
| 3 | 2009-06-05T04:31:11Z | 955,644 | <p>Make sure you define own functions for <strong>screen redraw</strong> and <strong>screen rotate</strong> callbacks. When you rotate the device, you have to manually rescale everything to fit the new screen size. Otherwise you might get that "half of screen" effect.</p>
<pre><code>
canvas = img = None
def cb_redraw(aRect=(0,0,0,0)):
''' Overwrite default screen redraw event handler '''
if img:
canvas.blit(img)
def cb_resize(aSize=(0,0,0,0)):
''' Overwrite default screen resize event handler '''
global img
img = graphics.Image.new(canvas.size)
appuifw.app.screen = 'full'
canvas = appuifw.Canvas(
resize_callback = cb_resize,
redraw_callback = cb_redraw)
appuifw.app.body = canvas
</code></pre>
| 4 | 2009-06-05T12:47:22Z | [
"python",
"symbian",
"pys60"
] |
Getting object's parent namespace in python? | 954,340 | <p>In python it's possible to use '.' in order to access object's dictionary items. For example:</p>
<pre><code>class test( object ) :
def __init__( self ) :
self.b = 1
def foo( self ) :
pass
obj = test()
a = obj.foo
</code></pre>
<p>From above example, having 'a' object, is it possible to get from it reference to 'obj' that is a parent namespace for 'foo' method assigned? For example, to change obj.b into 2?</p>
| 9 | 2009-06-05T05:03:01Z | 954,347 | <h2>Python 2.6+ (including Python 3)</h2>
<p>You can use the <a href="https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy" rel="nofollow"><code>__self__</code> property of a bound method</a> to access the instance that the method is bound to.</p>
<pre><code>>> a.__self__
<__main__.test object at 0x782d0>
>> a.__self__.b = 2
>> obj.b
2
</code></pre>
<h2>Python 2.2+ (Python 2.x only)</h2>
<p>You can also use the <code>im_self</code> property, but this is not forward compatible with Python 3.</p>
<pre><code>>> a.im_self
<__main__.test object at 0x782d0>
</code></pre>
| 14 | 2009-06-05T05:06:02Z | [
"python",
"python-datamodel"
] |
Getting object's parent namespace in python? | 954,340 | <p>In python it's possible to use '.' in order to access object's dictionary items. For example:</p>
<pre><code>class test( object ) :
def __init__( self ) :
self.b = 1
def foo( self ) :
pass
obj = test()
a = obj.foo
</code></pre>
<p>From above example, having 'a' object, is it possible to get from it reference to 'obj' that is a parent namespace for 'foo' method assigned? For example, to change obj.b into 2?</p>
| 9 | 2009-06-05T05:03:01Z | 954,514 | <p>On bound methods, you can use three special read-only parameters:</p>
<ul>
<li><strong>im_func</strong> which returns the (unbound) function object</li>
<li><strong>im_self</strong> which returns the object the function is bound to (class instance)</li>
<li><strong>im_class</strong> which returns the class of <em>im_self</em></li>
</ul>
<p>Testing around:</p>
<pre><code>class Test(object):
def foo(self):
pass
instance = Test()
instance.foo # <bound method Test.foo of <__main__.Test object at 0x1>>
instance.foo.im_func # <function foo at 0x2>
instance.foo.im_self # <__main__.Test object at 0x1>
instance.foo.im_class # <__main__.Test class at 0x3>
# A few remarks
instance.foo.im_self.__class__ == instance.foo.im_class # True
instance.foo.__name__ == instance.foo.im_func.__name__ # True
instance.foo.__doc__ == instance.foo.im_func.__doc__ # True
# Now, note this:
Test.foo.im_func != Test.foo # unbound method vs function
Test.foo.im_self is None
# Let's play with classmethods
class Extend(Test):
@classmethod
def bar(cls):
pass
extended = Extend()
# Be careful! Because it's a class method, the class is returned, not the instance
extended.bar.im_self # <__main__.Extend class at ...>
</code></pre>
<p>There is an interesting thing to note here, that gives you a hint on how the methods are being called:</p>
<pre><code>class Hint(object):
def foo(self, *args, **kwargs):
pass
@classmethod
def bar(cls, *args, **kwargs):
pass
instance = Hint()
# this will work with both class methods and instance methods:
for name in ['foo', 'bar']:
method = instance.__getattribute__(name)
# call the method
method.im_func(method.im_self, 1, 2, 3, fruit='banana')
</code></pre>
<p>Basically, <em>im_self</em> attribute of a bound method changes, to allow using it as the first parameter when calling <em>im_func</em></p>
| 17 | 2009-06-05T06:31:40Z | [
"python",
"python-datamodel"
] |
Getting object's parent namespace in python? | 954,340 | <p>In python it's possible to use '.' in order to access object's dictionary items. For example:</p>
<pre><code>class test( object ) :
def __init__( self ) :
self.b = 1
def foo( self ) :
pass
obj = test()
a = obj.foo
</code></pre>
<p>From above example, having 'a' object, is it possible to get from it reference to 'obj' that is a parent namespace for 'foo' method assigned? For example, to change obj.b into 2?</p>
| 9 | 2009-06-05T05:03:01Z | 954,619 | <p>since python2.6 synonyms for <code>im_self</code> and <code>im_func</code> are <code>__self__</code> and <code>__func__</code>, respectively. <code>im*</code> attributes are completely gone in py3k. so you would need to change it to:</p>
<pre><code>>> a.__self__
<__main__.test object at 0xb7b7d9ac>
>> a.__self__.b = 2
>> obj.b
2
</code></pre>
| 7 | 2009-06-05T07:16:59Z | [
"python",
"python-datamodel"
] |
Help with Django app and payment systems (general queries) | 954,478 | <p>So I'm working on an app in Django, however this is my first time venturing into advance integration for a webapp with payment systems (I used to work with paypal/2checkout so it was pretty no-skill-required).</p>
<p>My partners have chosen PaymentExpress, and there are several sets of API (all of which are pretty new to me) and they are as follows (<a href="http://www.paymentexpress.com/products/ecommerce/merchant_hosted.html" rel="nofollow">http://www.paymentexpress.com/products/ecommerce/merchant_hosted.html</a>)</p>
<p>1) PXPost
2) Software toolkit
3) Web Service</p>
<p>I would like to pick the brains of the many experts in this area, on what these various APIs are useful for and their disadvantages.</p>
<p>Of course, if there is a ready Django Pluggable/Snipplet that works with one of the above APIs above, I am open to exploring them too.</p>
<p>Thanks in advance!</p>
| 1 | 2009-06-05T06:17:35Z | 954,774 | <p>PXPost is the most straight-forward solution. You just communicate via HTTP POSTs and XML. You don't need any external dependencies, just <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a> and <a href="http://docs.python.org/library/xml.etree.elementtree.html?highlight=etree#module-xml.etree.ElementTree" rel="nofollow">ElementTree</a>. </p>
<p>Software toolkit can be used only on Windows platform, so it's not an option for you(or is it?). COM is also a nasty beast.</p>
<p>Web service is a more elegant PXPost. You won't need to build your own XML request, the SOAP protocol does that for you. It just downloads the WSDL where it's specified which methods web service exposes and generates Python module with web service's methods. You just then import the module and off you go. The problem is that it's not always easy to generate that Python module. If web service uses some custom data types it can get quite complicated. Check <a href="http://pywebsvcs.sourceforge.net/" rel="nofollow">this</a> for more. </p>
<p>So, I'd try with web service approach first, if that fails go with PXPost.</p>
| 0 | 2009-06-05T08:07:56Z | [
"python",
"django",
"payment"
] |
How to get files in a directory, including all subdirectories | 954,504 | <p>I'm trying to get a list of all log files (.log) in directory, including all subdirectories.</p>
| 15 | 2009-06-05T06:27:08Z | 954,517 | <p>Checkout <a href="http://ssscripting.wordpress.com/2009/03/03/python-recursive-directory-walker/">Python Recursive Directory Walker</a>. In short os.listdir() and os.walk() are your friends.</p>
| 7 | 2009-06-05T06:33:17Z | [
"python"
] |
How to get files in a directory, including all subdirectories | 954,504 | <p>I'm trying to get a list of all log files (.log) in directory, including all subdirectories.</p>
| 15 | 2009-06-05T06:27:08Z | 954,519 | <p>If You want to list in current directory, You can use something like:</p>
<pre><code>import os
for e in os.walk(os.getcwd()):
print e
</code></pre>
<p>Just change the</p>
<pre><code>os.getcwd()
</code></pre>
<p>to other path to get results there.</p>
| 1 | 2009-06-05T06:34:56Z | [
"python"
] |
How to get files in a directory, including all subdirectories | 954,504 | <p>I'm trying to get a list of all log files (.log) in directory, including all subdirectories.</p>
| 15 | 2009-06-05T06:27:08Z | 954,522 | <pre><code>import os
import os.path
for dirpath, dirnames, filenames in os.walk("."):
for filename in [f for f in filenames if f.endswith(".log")]:
print os.path.join(dirpath, filename)
</code></pre>
| 28 | 2009-06-05T06:35:19Z | [
"python"
] |
How to get files in a directory, including all subdirectories | 954,504 | <p>I'm trying to get a list of all log files (.log) in directory, including all subdirectories.</p>
| 15 | 2009-06-05T06:27:08Z | 954,948 | <p>You can also use the glob module along with os.walk.</p>
<pre><code>import os
from glob import glob
files = []
start_dir = os.getcwd()
pattern = "*.log"
for dir,_,_ in os.walk(start_dir):
files.extend(glob(os.path.join(dir,pattern)))
</code></pre>
| 5 | 2009-06-05T09:08:38Z | [
"python"
] |
By System command | 954,823 | <p>By using system command i want to open '.py' in the notepad.
Ex
assume i have "Fact.py" file.
Now i want to write a program which will open this file in notepad and we can edit this file.</p>
| 0 | 2009-06-05T08:28:09Z | 954,828 | <pre><code>import os
os.system("notepad.exe fact.py")
</code></pre>
<p>should do it, assuming the Notepad program is in your system's path.</p>
| 1 | 2009-06-05T08:30:10Z | [
"python"
] |
By System command | 954,823 | <p>By using system command i want to open '.py' in the notepad.
Ex
assume i have "Fact.py" file.
Now i want to write a program which will open this file in notepad and we can edit this file.</p>
| 0 | 2009-06-05T08:28:09Z | 954,835 | <p>It's best to use subprocess for this, since this will avoid having to deal with quoting files containing spaces etc for the shell.</p>
<pre><code>import subprocess
subprocess.call(['notepad','Fact.py'])
</code></pre>
| 8 | 2009-06-05T08:33:14Z | [
"python"
] |
How do I use raw_input in Python 3 | 954,834 | <pre><code>import sys
print (sys.platform)
print (2 ** 100)
raw_input( )
</code></pre>
<p>I am using Python 3.1 and can't get the raw_input to "freeze" the dos pop-up. The book I'm reading is for 2.5 and I'm using 3.1</p>
<p>What should I do to fix this?</p>
| 220 | 2009-06-05T08:32:23Z | 954,840 | <p><code>raw_input()</code> was renamed to <code>input()</code></p>
<p>From <a href="http://docs.python.org/dev/py3k/whatsnew/3.0.html">http://docs.python.org/dev/py3k/whatsnew/3.0.html</a></p>
| 405 | 2009-06-05T08:35:38Z | [
"python",
"python-3.x"
] |
How do I use raw_input in Python 3 | 954,834 | <pre><code>import sys
print (sys.platform)
print (2 ** 100)
raw_input( )
</code></pre>
<p>I am using Python 3.1 and can't get the raw_input to "freeze" the dos pop-up. The book I'm reading is for 2.5 and I'm using 3.1</p>
<p>What should I do to fix this?</p>
| 220 | 2009-06-05T08:32:23Z | 7,321,970 | <p>This works in Python 3.x and 2.x:</p>
<pre><code># Fix Python 2.x.
try: input = raw_input
except NameError: pass
print("Hi " + input("Say something: "))
</code></pre>
| 66 | 2011-09-06T14:59:18Z | [
"python",
"python-3.x"
] |
How do I use raw_input in Python 3 | 954,834 | <pre><code>import sys
print (sys.platform)
print (2 ** 100)
raw_input( )
</code></pre>
<p>I am using Python 3.1 and can't get the raw_input to "freeze" the dos pop-up. The book I'm reading is for 2.5 and I'm using 3.1</p>
<p>What should I do to fix this?</p>
| 220 | 2009-06-05T08:32:23Z | 9,411,224 | <p>In Python 3.xx you just need <code>input()</code> not <code>raw_input()</code></p>
| 5 | 2012-02-23T10:31:18Z | [
"python",
"python-3.x"
] |
How do I use raw_input in Python 3 | 954,834 | <pre><code>import sys
print (sys.platform)
print (2 ** 100)
raw_input( )
</code></pre>
<p>I am using Python 3.1 and can't get the raw_input to "freeze" the dos pop-up. The book I'm reading is for 2.5 and I'm using 3.1</p>
<p>What should I do to fix this?</p>
| 220 | 2009-06-05T08:32:23Z | 9,411,780 | <p>As others have indicated, the <code>raw_input</code> function has been renamed to <code>input</code> in Python 3.0, and you really would be better served by a more up-to-date book, but I want to point out that there are better ways to see the output of your script.</p>
<p>From your description, I think you're using Windows, you've saved a <code>.py</code> file and then you're double-clicking on it to run it. The terminal window that pops up closes as soon as your program ends, so you can't see what the result of your program was. To solve this, your book recommends adding a <code>raw_input</code> / <code>input</code> statement to wait until the user presses enter. However, as you've seen, if something goes wrong, such as an error in your program, that statement won't be executed and the window will close without you being able to see what went wrong. You might find it easier to use a command-prompt or IDLE.</p>
<h2>Use a command-prompt</h2>
<p>When you're looking at the folder window that contains your Python program, hold down shift and right-click anywhere in the white background area of the window. The menu that pops up should contain an entry "Open command window here". (I think this works on Windows Vista and Windows 7.) This will open a command-prompt window that looks something like this:</p>
<pre><code> Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\Weeble\My Python Program>_
</code></pre>
<p>To run your program, type the following (substituting your script name):</p>
<pre><code> python myscript.py
</code></pre>
<p>...and press enter. (If you get an error that "python" is not a recognized command, see <a href="http://showmedo.com/videotutorials/video?name=960000&fromSeriesID=96">http://showmedo.com/videotutorials/video?name=960000&fromSeriesID=96</a> ) When your program finishes running, whether it completes successfully or not, the window will remain open and the command-prompt will appear again for you to type another command. If you want to run your program again, you can press the up arrow to recall the previous command you entered and press enter to run it again, rather than having to type out the file name every time.</p>
<h2>Use IDLE</h2>
<p>IDLE is a simple program editor that comes installed with Python. Among other features it can run your programs in a window. Right-click on your <code>.py</code> file and choose "Edit in IDLE". When your program appears in the editor, press F5 or choose "Run module" from the "Run" menu. Your program will run in a window that stays open after your program ends, and in which you can enter Python commands to run immediately.</p>
| 11 | 2012-02-23T11:05:27Z | [
"python",
"python-3.x"
] |
How do I use raw_input in Python 3 | 954,834 | <pre><code>import sys
print (sys.platform)
print (2 ** 100)
raw_input( )
</code></pre>
<p>I am using Python 3.1 and can't get the raw_input to "freeze" the dos pop-up. The book I'm reading is for 2.5 and I'm using 3.1</p>
<p>What should I do to fix this?</p>
| 220 | 2009-06-05T08:32:23Z | 18,332,097 | <p>Timmerman's solution works great when running the code, but if you don't want to get <code>Undefined name</code> errors when using pyflakes or a similar linter you could use the following instead:</p>
<pre><code>try:
import __builtin__
input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
pass
</code></pre>
| 4 | 2013-08-20T09:54:29Z | [
"python",
"python-3.x"
] |
How do I use raw_input in Python 3 | 954,834 | <pre><code>import sys
print (sys.platform)
print (2 ** 100)
raw_input( )
</code></pre>
<p>I am using Python 3.1 and can't get the raw_input to "freeze" the dos pop-up. The book I'm reading is for 2.5 and I'm using 3.1</p>
<p>What should I do to fix this?</p>
| 220 | 2009-06-05T08:32:23Z | 25,972,524 | <p>Here's a piece of code I put in my scripts that I wan't to run in py2/3-agnostic environment:</p>
<pre><code># Thank you, python2-3 team, for making such a fantastic mess with
# input/raw_input :-)
real_raw_input = vars(__builtins__).get('raw_input',input)
</code></pre>
<p>Now you can use real_raw_input. It's quite expensive but short and readable. Using raw input is usually time expensive (waiting for input), so it's not important.</p>
<p>In theory, you can even assign raw_input instead of real_raw_input but there might be modules that check existence of raw_input and behave accordingly. It's better stay on the safe side.</p>
| 3 | 2014-09-22T11:02:21Z | [
"python",
"python-3.x"
] |
How do I use raw_input in Python 3 | 954,834 | <pre><code>import sys
print (sys.platform)
print (2 ** 100)
raw_input( )
</code></pre>
<p>I am using Python 3.1 and can't get the raw_input to "freeze" the dos pop-up. The book I'm reading is for 2.5 and I'm using 3.1</p>
<p>What should I do to fix this?</p>
| 220 | 2009-06-05T08:32:23Z | 31,687,067 | <p>A reliable way to address this is</p>
<pre><code>from six.moves import input
</code></pre>
<p><a href="http://pythonhosted.org/six/">six</a> is a module which patches over many of the 2/3 common code base pain points.</p>
| 8 | 2015-07-28T21:05:42Z | [
"python",
"python-3.x"
] |
How can I tell if a certain key was pressed in Python? | 954,933 | <pre><code>import sys
print (sys.platform)
print (2 ** 100)
input('press Enter to exit')
</code></pre>
<p>Suppose I wanted to use the number 1 as the button that must be pressed to exit. How would I go about doing this?</p>
| 2 | 2009-06-05T09:04:14Z | 954,951 | <p>Something like this will do what you want:</p>
<pre><code>while(raw_input('Press "1" to exit.') != '1'):
pass
</code></pre>
| 1 | 2009-06-05T09:10:11Z | [
"python"
] |
How can I tell if a certain key was pressed in Python? | 954,933 | <pre><code>import sys
print (sys.platform)
print (2 ** 100)
input('press Enter to exit')
</code></pre>
<p>Suppose I wanted to use the number 1 as the button that must be pressed to exit. How would I go about doing this?</p>
| 2 | 2009-06-05T09:04:14Z | 954,955 | <p>Something like this?</p>
<p><a href="http://mail.python.org/pipermail/python-list/1999-October/014262.html" rel="nofollow">http://mail.python.org/pipermail/python-list/1999-October/014262.html</a></p>
<p>Not so clean, but doable.</p>
| 2 | 2009-06-05T09:10:58Z | [
"python"
] |
How can I tell if a certain key was pressed in Python? | 954,933 | <pre><code>import sys
print (sys.platform)
print (2 ** 100)
input('press Enter to exit')
</code></pre>
<p>Suppose I wanted to use the number 1 as the button that must be pressed to exit. How would I go about doing this?</p>
| 2 | 2009-06-05T09:04:14Z | 954,996 | <p>If you're building a command line app, why not use one of the libraries that help you build one.</p>
<p>For example:</p>
<ul>
<li><a href="http://docs.python.org/library/curses.html" rel="nofollow">curses</a> </li>
<li><a href="http://excess.org/urwid/" rel="nofollow">urwid</a>.</li>
</ul>
| 2 | 2009-06-05T09:23:20Z | [
"python"
] |
How do I use a Python library in my Java application? | 954,950 | <p>What are the basic nuts and bolts of calling (running? interpreting? what can you do?) Python code from a Java program? Are there many ways to do it?</p>
| 1 | 2009-06-05T09:10:00Z | 954,958 | <p>You can <a href="http://www.jython.org/docs/embedding.html" rel="nofollow">embed Jython</a> within your Java application, rather than spawning off a separate process. Provided your library is <a href="http://www.jython.org/docs/differences.html" rel="nofollow">compatible</a> with Jython, that would seem the most logical place to start.</p>
| 4 | 2009-06-05T09:11:42Z | [
"java",
"python",
"jython"
] |
How do I use a Python library in my Java application? | 954,950 | <p>What are the basic nuts and bolts of calling (running? interpreting? what can you do?) Python code from a Java program? Are there many ways to do it?</p>
| 1 | 2009-06-05T09:10:00Z | 954,987 | <p>Apart from embedding Jython as mentioned by Brian, you have these options as well.</p>
<p>Java 1.6 has inbuilt support for scripting.
You can find more info <a href="http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/" rel="nofollow">here</a>.</p>
<p>Spring also provides excellent support for scripting. JRuby, Groovy are supported by Spring Scripting. You can find info <a href="http://www.briggs.net.nz/log/2007/11/01/scripting-in-spring/" rel="nofollow">here</a>.</p>
| 2 | 2009-06-05T09:20:03Z | [
"java",
"python",
"jython"
] |
How do I use a Python library in my Java application? | 954,950 | <p>What are the basic nuts and bolts of calling (running? interpreting? what can you do?) Python code from a Java program? Are there many ways to do it?</p>
| 1 | 2009-06-05T09:10:00Z | 955,010 | <p>And if none of the other alternatives mentioned (Jython, Spring) work, you can always run an external CPython interpreter and communicate with the JVM through:</p>
<ul>
<li>CORBA</li>
<li>Sockets</li>
<li>Pipes</li>
<li>Temporary files</li>
</ul>
<p>Also maybe you would take a look at <a href="http://wiki.services.openoffice.org/wiki/Uno" rel="nofollow">OpenOffice's UNO</a>... I think it could be used outside the suite.</p>
| 0 | 2009-06-05T09:26:36Z | [
"java",
"python",
"jython"
] |
My regex in python isn't recursing properly | 954,989 | <p>I'm suppose to capture everything inside a tag and the next lines after it, but it's suppose to stop the next time it meets a bracket. What am i doing wrong?</p>
<pre><code>import re #regex
regex = re.compile(r"""
^ # Must start in a newline first
\[\b(.*)\b\] # Get what's enclosed in brackets
\n # only capture bracket if a newline is next
(\b(?:.|\s)*(?!\[)) # should read: anyword that doesn't precede a bracket
""", re.MULTILINE | re.VERBOSE)
haystack = """
[tab1]
this is captured
but this is suppose to be captured too!
@[this should be taken though as this is in the content]
[tab2]
help me
write a better RE
"""
m = regex.findall(haystack)
print m
</code></pre>
<p><strong>what im trying to get is:</strong><br />
<strong>[('tab1', 'this is captured\nbut this is suppose to be captured too!\n@[this should be taken though as this is in the content]\n', '[tab2]','help me\nwrite a better RE\n')]</strong></p>
<p>edit:</p>
<pre><code>regex = re.compile(r"""
^ # Must start in a newline first
\[(.*?)\] # Get what's enclosed in brackets
\n # only capture bracket if a newline is next
([^\[]*) # stop reading at opening bracket
""", re.MULTILINE | re.VERBOSE)
</code></pre>
<p>this seems to work but it's also trimming the brackets inside the content.</p>
| 2 | 2009-06-05T09:21:26Z | 955,001 | <p>Python regex doesn't support recursion afaik.</p>
<p>EDIT: but in your case this would work:</p>
<pre><code>regex = re.compile(r"""
^ # Must start in a newline first
\[(.*?)\] # Get what's enclosed in brackets
\n # only capture bracket if a newline is next
([^\[]*) # stop reading at opening bracket
""", re.MULTILINE | re.VERBOSE)
</code></pre>
<p>EDIT 2: yes, it doesn't work properly.</p>
<pre><code>import re
regex = re.compile(r"""
(?:^|\n)\[ # tag's opening bracket
([^\]\n]*) # 1. text between brackets
\]\n # tag's closing bracket
(.*?) # 2. text between the tags
(?=\n\[[^\]\n]*\]\n|$) # until tag or end of string but don't consume it
""", re.DOTALL | re.VERBOSE)
haystack = """[tag1]
this is captured [not a tag[
but this is suppose to be captured too!
[another non-tag
[tag2]
help me
write a better RE[[[]
"""
print regex.findall(haystack)
</code></pre>
<p>I do agree with viraptor though. Regex are cool but you can't check your file for errors with them. A hybrid perhaps? :P</p>
<pre><code>tag_re = re.compile(r'^\[([^\]\n]*)\]$', re.MULTILINE)
tags = list(tag_re.finditer(haystack))
result = {}
for (mo1, mo2) in zip(tags[:-1], tags[1:]):
result[mo1.group(1)] = haystack[mo1.end(1)+1:mo2.start(1)-1].strip()
result[mo2.group(1)] = haystack[mo2.end(1)+1:].strip()
print result
</code></pre>
<p>EDIT 3: That's because <code>^</code> character means negative match only inside <code>[^squarebrackets]</code>. Everywhere else it means string start (or line start with <code>re.MULTILINE</code>). There's no good way for negative string matching in regex, only character.</p>
| 3 | 2009-06-05T09:24:39Z | [
"python",
"regex",
"recursion"
] |
My regex in python isn't recursing properly | 954,989 | <p>I'm suppose to capture everything inside a tag and the next lines after it, but it's suppose to stop the next time it meets a bracket. What am i doing wrong?</p>
<pre><code>import re #regex
regex = re.compile(r"""
^ # Must start in a newline first
\[\b(.*)\b\] # Get what's enclosed in brackets
\n # only capture bracket if a newline is next
(\b(?:.|\s)*(?!\[)) # should read: anyword that doesn't precede a bracket
""", re.MULTILINE | re.VERBOSE)
haystack = """
[tab1]
this is captured
but this is suppose to be captured too!
@[this should be taken though as this is in the content]
[tab2]
help me
write a better RE
"""
m = regex.findall(haystack)
print m
</code></pre>
<p><strong>what im trying to get is:</strong><br />
<strong>[('tab1', 'this is captured\nbut this is suppose to be captured too!\n@[this should be taken though as this is in the content]\n', '[tab2]','help me\nwrite a better RE\n')]</strong></p>
<p>edit:</p>
<pre><code>regex = re.compile(r"""
^ # Must start in a newline first
\[(.*?)\] # Get what's enclosed in brackets
\n # only capture bracket if a newline is next
([^\[]*) # stop reading at opening bracket
""", re.MULTILINE | re.VERBOSE)
</code></pre>
<p>this seems to work but it's also trimming the brackets inside the content.</p>
| 2 | 2009-06-05T09:21:26Z | 955,024 | <p>Does this do what you want?</p>
<pre><code>regex = re.compile(r"""
^ # Must start in a newline first
\[\b(.*)\b\] # Get what's enclosed in brackets
\n # only capture bracket if a newline is next
([^[]*)
""", re.MULTILINE | re.VERBOSE)
</code></pre>
<p>This gives a list of tuples (one 2-tuple per match). If you want a flattened tuple you can write:</p>
<pre><code>m = sum(regex.findall(haystack), ())
</code></pre>
| 2 | 2009-06-05T09:32:38Z | [
"python",
"regex",
"recursion"
] |
My regex in python isn't recursing properly | 954,989 | <p>I'm suppose to capture everything inside a tag and the next lines after it, but it's suppose to stop the next time it meets a bracket. What am i doing wrong?</p>
<pre><code>import re #regex
regex = re.compile(r"""
^ # Must start in a newline first
\[\b(.*)\b\] # Get what's enclosed in brackets
\n # only capture bracket if a newline is next
(\b(?:.|\s)*(?!\[)) # should read: anyword that doesn't precede a bracket
""", re.MULTILINE | re.VERBOSE)
haystack = """
[tab1]
this is captured
but this is suppose to be captured too!
@[this should be taken though as this is in the content]
[tab2]
help me
write a better RE
"""
m = regex.findall(haystack)
print m
</code></pre>
<p><strong>what im trying to get is:</strong><br />
<strong>[('tab1', 'this is captured\nbut this is suppose to be captured too!\n@[this should be taken though as this is in the content]\n', '[tab2]','help me\nwrite a better RE\n')]</strong></p>
<p>edit:</p>
<pre><code>regex = re.compile(r"""
^ # Must start in a newline first
\[(.*?)\] # Get what's enclosed in brackets
\n # only capture bracket if a newline is next
([^\[]*) # stop reading at opening bracket
""", re.MULTILINE | re.VERBOSE)
</code></pre>
<p>this seems to work but it's also trimming the brackets inside the content.</p>
| 2 | 2009-06-05T09:21:26Z | 959,571 | <p>First of all why a regex if you're trying to parse? As you can see you cannot find the source of the problem yourself, because regex gives no feedback. Also you don't have any recursion in that RE.</p>
<p>Make your life simple:</p>
<pre><code>def ini_parse(src):
in_block = None
contents = {}
for line in src.split("\n"):
if line.startswith('[') and line.endswith(']'):
in_block = line[1:len(line)-1]
contents[in_block] = ""
elif in_block is not None:
contents[in_block] += line + "\n"
elif line.strip() != "":
raise Exception("content out of block")
return contents
</code></pre>
<p>You get error handling with exceptions and the ability to debug execution as a bonus. Also you get a dictionary as a result and can handle duplicate sections while processing. My result:</p>
<pre><code>{'tab2': 'help me\nwrite a better RE\n\n',
'tab1': 'this is captured\nbut this is suppose to be captured too!\n@[this should be taken though as this is in the content]\n\n'}
</code></pre>
<p>RE is much overused these days...</p>
| 3 | 2009-06-06T12:15:02Z | [
"python",
"regex",
"recursion"
] |
How do I run "dot" as a command from Python? | 955,504 | <p>I am using Python on Mac OSX Leopard.</p>
<p>I am trying to run the program 'dot' (part of Graphviz) from Python:</p>
<pre><code># -*- coding: utf-8 -*-
import os
print os.environ['PATH']
print os.system("ls >> a.txt")
print os.system("dot -o9.png -Tpng ./6.dot")
</code></pre>
<p>The command "ls" is there just to make sure that python is in the correct directory. It is. The result that I get is:</p>
<blockquote>
<p>/usr/bin:/bin:/usr/sbin:/sbin
0
32512</p>
</blockquote>
<p>My understanding is that 32512 error means that python could not find the file, and since the file 6.dot is there (If I run "dot -o9.png -Tpng ./6.dot" from the terminal I receive no error, and 9.png gets produced), I assume Python can't find the dot file.</p>
<p>I probably need to add the dot file to the path. But I don't know where is it. If I run: </p>
<pre><code>whereis dot
</code></pre>
<p>I receive no answer.</p>
<p>How can I find the dot executable?<br />
Alternatively, can I run the dot program as a command from inside Python?</p>
| 4 | 2009-06-05T11:55:09Z | 955,523 | <p><code>whereis</code> locates man pages, <code>which</code> locates binaries. So try <code>which dot</code>.</p>
| 10 | 2009-06-05T12:01:06Z | [
"python",
"osx",
"path",
"graphviz",
"dot"
] |
How do I run "dot" as a command from Python? | 955,504 | <p>I am using Python on Mac OSX Leopard.</p>
<p>I am trying to run the program 'dot' (part of Graphviz) from Python:</p>
<pre><code># -*- coding: utf-8 -*-
import os
print os.environ['PATH']
print os.system("ls >> a.txt")
print os.system("dot -o9.png -Tpng ./6.dot")
</code></pre>
<p>The command "ls" is there just to make sure that python is in the correct directory. It is. The result that I get is:</p>
<blockquote>
<p>/usr/bin:/bin:/usr/sbin:/sbin
0
32512</p>
</blockquote>
<p>My understanding is that 32512 error means that python could not find the file, and since the file 6.dot is there (If I run "dot -o9.png -Tpng ./6.dot" from the terminal I receive no error, and 9.png gets produced), I assume Python can't find the dot file.</p>
<p>I probably need to add the dot file to the path. But I don't know where is it. If I run: </p>
<pre><code>whereis dot
</code></pre>
<p>I receive no answer.</p>
<p>How can I find the dot executable?<br />
Alternatively, can I run the dot program as a command from inside Python?</p>
| 4 | 2009-06-05T11:55:09Z | 955,534 | <p>Troubleshooting tips: </p>
<p>A. add </p>
<p><code>print os.getcwd()</code></p>
<p>on the line before os.system("dot etc.</p>
<p>Just to make sure that the current directory is the one with the <code>6.dot</code> file.</p>
<p>B. Make sure that the <code>dot</code> program is in your path.</p>
<p><code>which dot</code></p>
<p>C. Use the full path to the <code>dot</code> program in your os.system command, see what happens then.</p>
| 2 | 2009-06-05T12:03:29Z | [
"python",
"osx",
"path",
"graphviz",
"dot"
] |
How do I run "dot" as a command from Python? | 955,504 | <p>I am using Python on Mac OSX Leopard.</p>
<p>I am trying to run the program 'dot' (part of Graphviz) from Python:</p>
<pre><code># -*- coding: utf-8 -*-
import os
print os.environ['PATH']
print os.system("ls >> a.txt")
print os.system("dot -o9.png -Tpng ./6.dot")
</code></pre>
<p>The command "ls" is there just to make sure that python is in the correct directory. It is. The result that I get is:</p>
<blockquote>
<p>/usr/bin:/bin:/usr/sbin:/sbin
0
32512</p>
</blockquote>
<p>My understanding is that 32512 error means that python could not find the file, and since the file 6.dot is there (If I run "dot -o9.png -Tpng ./6.dot" from the terminal I receive no error, and 9.png gets produced), I assume Python can't find the dot file.</p>
<p>I probably need to add the dot file to the path. But I don't know where is it. If I run: </p>
<pre><code>whereis dot
</code></pre>
<p>I receive no answer.</p>
<p>How can I find the dot executable?<br />
Alternatively, can I run the dot program as a command from inside Python?</p>
| 4 | 2009-06-05T11:55:09Z | 955,536 | <p>You need to add the path to the 'dot' executable in Python's environment. You can do this by modifying the PATH variable in os.environ</p>
| 3 | 2009-06-05T12:04:09Z | [
"python",
"osx",
"path",
"graphviz",
"dot"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.