title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
python regular expression to split paragraphs | 116,494 | <p>How would one write a regular expression to use in python to split paragraphs?</p>
<p>A paragraph is defined by 2 linebreaks (\n). But one can have any ammount of spaces/tabs together with the line breaks, and it still should be considered as a paragraph.</p>
<p>I am using python so the solution can use python's <a href="http://docs.python.org/lib/re-syntax.html" rel="nofollow" title="Python re syntax">regular expression syntax</a> which is extended. (can make use of <code>(?P...)</code> stuff)</p>
<h1>Examples:</h1>
<pre><code>the_str = 'paragraph1\n\nparagraph2'
# splitting should yield ['paragraph1', 'paragraph2']
the_str = 'p1\n\t\np2\t\n\tstill p2\t \n \n\tp3'
# should yield ['p1', 'p2\t\n\tstill p2', 'p3']
the_str = 'p1\n\n\n\tp2'
# should yield ['p1', '\n\tp2']
</code></pre>
<p>The best I could come with is: <code>r'[ \t\r\f\v]*\n[ \t\r\f\v]*\n[ \t\r\f\v]*'</code> but that is ugly. Anything better?</p>
<p><strong>EDIT</strong>:</p>
<h1>Suggestions rejected:</h1>
<p><code>r'\s*?\n\s*?\n\s*?'</code> -> That would make example 2 and 3 fail, since <code>\s</code> includes <code>\n</code>, so it would allow paragraph breaks with more than 2 <code>\n</code>s.</p>
| 3 | 2008-09-22T18:10:41Z | 116,557 | <p>Almost the same, but using non-greedy quantifiers and taking advantage of the whitespace sequence.</p>
<pre><code>\s*?\n\s*?\n\s*?
</code></pre>
| 0 | 2008-09-22T18:18:09Z | [
"python",
"regex",
"parsing",
"text",
"split"
] |
python regular expression to split paragraphs | 116,494 | <p>How would one write a regular expression to use in python to split paragraphs?</p>
<p>A paragraph is defined by 2 linebreaks (\n). But one can have any ammount of spaces/tabs together with the line breaks, and it still should be considered as a paragraph.</p>
<p>I am using python so the solution can use python's <a href="http://docs.python.org/lib/re-syntax.html" rel="nofollow" title="Python re syntax">regular expression syntax</a> which is extended. (can make use of <code>(?P...)</code> stuff)</p>
<h1>Examples:</h1>
<pre><code>the_str = 'paragraph1\n\nparagraph2'
# splitting should yield ['paragraph1', 'paragraph2']
the_str = 'p1\n\t\np2\t\n\tstill p2\t \n \n\tp3'
# should yield ['p1', 'p2\t\n\tstill p2', 'p3']
the_str = 'p1\n\n\n\tp2'
# should yield ['p1', '\n\tp2']
</code></pre>
<p>The best I could come with is: <code>r'[ \t\r\f\v]*\n[ \t\r\f\v]*\n[ \t\r\f\v]*'</code> but that is ugly. Anything better?</p>
<p><strong>EDIT</strong>:</p>
<h1>Suggestions rejected:</h1>
<p><code>r'\s*?\n\s*?\n\s*?'</code> -> That would make example 2 and 3 fail, since <code>\s</code> includes <code>\n</code>, so it would allow paragraph breaks with more than 2 <code>\n</code>s.</p>
| 3 | 2008-09-22T18:10:41Z | 116,621 | <p>Are you trying to deduce the structure of a document in plain test? Are you doing what <a href="http://docutils.sourceforge.net/" rel="nofollow">docutils</a> does?</p>
<p>You might be able to simply use the <a href="http://docutils.sourceforge.net/docs/dev/hacking.html#parsing-the-document" rel="nofollow">Docutils parser</a> rather than roll your own.</p>
| 2 | 2008-09-22T18:28:28Z | [
"python",
"regex",
"parsing",
"text",
"split"
] |
python regular expression to split paragraphs | 116,494 | <p>How would one write a regular expression to use in python to split paragraphs?</p>
<p>A paragraph is defined by 2 linebreaks (\n). But one can have any ammount of spaces/tabs together with the line breaks, and it still should be considered as a paragraph.</p>
<p>I am using python so the solution can use python's <a href="http://docs.python.org/lib/re-syntax.html" rel="nofollow" title="Python re syntax">regular expression syntax</a> which is extended. (can make use of <code>(?P...)</code> stuff)</p>
<h1>Examples:</h1>
<pre><code>the_str = 'paragraph1\n\nparagraph2'
# splitting should yield ['paragraph1', 'paragraph2']
the_str = 'p1\n\t\np2\t\n\tstill p2\t \n \n\tp3'
# should yield ['p1', 'p2\t\n\tstill p2', 'p3']
the_str = 'p1\n\n\n\tp2'
# should yield ['p1', '\n\tp2']
</code></pre>
<p>The best I could come with is: <code>r'[ \t\r\f\v]*\n[ \t\r\f\v]*\n[ \t\r\f\v]*'</code> but that is ugly. Anything better?</p>
<p><strong>EDIT</strong>:</p>
<h1>Suggestions rejected:</h1>
<p><code>r'\s*?\n\s*?\n\s*?'</code> -> That would make example 2 and 3 fail, since <code>\s</code> includes <code>\n</code>, so it would allow paragraph breaks with more than 2 <code>\n</code>s.</p>
| 3 | 2008-09-22T18:10:41Z | 116,622 | <p>Unfortunately there's no nice way to write "space but not a newline".</p>
<p>I think the best you can do is add some space with the <code>x</code> modifier and try to factor out the ugliness a bit, but that's questionable: <code>(?x) (?: [ \t\r\f\v]*? \n ){2} [ \t\r\f\v]*?</code></p>
<p>You could also try creating a subrule just for the character class and interpolating it three times.</p>
| 3 | 2008-09-22T18:28:47Z | [
"python",
"regex",
"parsing",
"text",
"split"
] |
python regular expression to split paragraphs | 116,494 | <p>How would one write a regular expression to use in python to split paragraphs?</p>
<p>A paragraph is defined by 2 linebreaks (\n). But one can have any ammount of spaces/tabs together with the line breaks, and it still should be considered as a paragraph.</p>
<p>I am using python so the solution can use python's <a href="http://docs.python.org/lib/re-syntax.html" rel="nofollow" title="Python re syntax">regular expression syntax</a> which is extended. (can make use of <code>(?P...)</code> stuff)</p>
<h1>Examples:</h1>
<pre><code>the_str = 'paragraph1\n\nparagraph2'
# splitting should yield ['paragraph1', 'paragraph2']
the_str = 'p1\n\t\np2\t\n\tstill p2\t \n \n\tp3'
# should yield ['p1', 'p2\t\n\tstill p2', 'p3']
the_str = 'p1\n\n\n\tp2'
# should yield ['p1', '\n\tp2']
</code></pre>
<p>The best I could come with is: <code>r'[ \t\r\f\v]*\n[ \t\r\f\v]*\n[ \t\r\f\v]*'</code> but that is ugly. Anything better?</p>
<p><strong>EDIT</strong>:</p>
<h1>Suggestions rejected:</h1>
<p><code>r'\s*?\n\s*?\n\s*?'</code> -> That would make example 2 and 3 fail, since <code>\s</code> includes <code>\n</code>, so it would allow paragraph breaks with more than 2 <code>\n</code>s.</p>
| 3 | 2008-09-22T18:10:41Z | 123,806 | <p>Not a regexp but really elegant:</p>
<pre><code>from itertools import groupby
def paragraph(lines) :
for group_separator, line_iteration in groupby(lines.splitlines(True), key = str.isspace) :
if not group_separator :
yield ''.join(line_iteration)
for p in paragraph('p1\n\t\np2\t\n\tstill p2\t \n \n\tp'):
print repr(p)
'p1\n'
'p2\t\n\tstill p2\t \n'
'\tp3'
</code></pre>
<p>It's up to you to strip the output as you need it of course.</p>
<p>Inspired from the famous "Python Cookbook" ;-)</p>
| 1 | 2008-09-23T20:54:44Z | [
"python",
"regex",
"parsing",
"text",
"split"
] |
How do you create an osx application/dmg from a python package? | 116,657 | <p>I want to create a mac osx application from python package and then put it in a disk image. </p>
<p>Because I load some resources out of the package, the package should <strong>not</strong> reside in a zip file.</p>
<p>The resulting disk image should display the background picture to "drag here -> applications" for installation.</p>
| 23 | 2008-09-22T18:35:28Z | 116,901 | <p>I don't know the correct way to do it, but this manual method is the approach I've used for simple scripts which seems to have preformed suitably.</p>
<p>I'll assume that whatever directory I'm in, the Python files for my program are in the relative <code>src/</code> directory, and that the file I want to execute (which has the proper shebang and execute permissions) is named <code>main.py</code>.</p>
<pre>
$ mkdir -p MyApplication.app/Contents/MacOS
$ mv src/* MyApplication.app/Contents/MacOS
$ cd MyApplication.app/Contents/MacOS
$ mv main.py MyApplication
</pre>
<p>At this point we have an application bundle which, as far as I know, should work on any Mac OS system with Python installed (which I think it has by default). It doesn't have an icon or anything, that requires adding some more metadata to the package which is unnecessary for my purposes and I'm not familiar with.</p>
<p>To create the drag-and-drop installer is quite simple. Use Disk Utility to create a New Disk Image of approximately the size you require to store your application. Open it up, copy your application and an alias of <code>/Applications</code> to the drive, then use View Options to position them as you want.</p>
<p>The drag-and-drop message is just a background of the disk image, which you can also specify in View Options. I haven't done it before, but I'd assume that after you whip up an image in your editor of choice you could copy it over, set it as the background and then use <code>chflags hidden</code> to prevent it from cluttering up your nice window.</p>
<p>I know these aren't the clearest, simplest or most detailed instructions out there, but I hope somebody may find them useful.</p>
| 7 | 2008-09-22T19:19:30Z | [
"python",
"osx",
"packaging"
] |
Best practices for manipulating database result sets in Python? | 116,894 | <p>I am writing a simple Python web application that consists of several pages of business data formatted for the iPhone. I'm comfortable programming Python, but I'm not very familiar with Python "idiom," especially regarding classes and objects. Python's object oriented design differs somewhat from other languages I've worked with. So, even though my application is working, I'm curious whether there is a better way to accomplish my goals.</p>
<p>Specifics: How does one typically implement the request-transform-render database workflow in Python? Currently, I am using pyodbc to fetch data, copying the results into attributes on an object, performing some calculations and merges using a list of these objects, then rendering the output from the list of objects. (Sample code below, SQL queries redacted.) Is this sane? Is there a better way? Are there any specific "gotchas" I've stumbled into in my relative ignorance of Python? I'm particularly concerned about how I've implemented the list of rows using the empty "Record" class.</p>
<pre><code>class Record(object):
pass
def calculate_pnl(records, node_prices):
for record in records:
try:
# fill RT and DA prices from the hash retrieved above
if hasattr(record, 'sink') and record.sink:
record.da = node_prices[record.sink][0] - node_prices[record.id][0]
record.rt = node_prices[record.sink][1] - node_prices[record.id][1]
else:
record.da = node_prices[record.id][0]
record.rt = node_prices[record.id][1]
# calculate dependent values: RT-DA and PNL
record.rtda = record.rt - record.da
record.pnl = record.rtda * record.mw
except:
print sys.exc_info()
def map_rows(cursor, mappings, callback=None):
records = []
for row in cursor:
record = Record()
for field, attr in mappings.iteritems():
setattr(record, attr, getattr(row, field, None))
if not callback or callback(record):
records.append(record)
return records
def get_positions(cursor):
# get the latest position time
cursor.execute("SELECT latest data time")
time = cursor.fetchone().time
hour = eelib.util.get_hour_ending(time)
# fetch the current positions
cursor.execute("SELECT stuff FROM atable", (hour))
# read the rows
nodes = {}
def record_callback(record):
if abs(record.mw) > 0:
if record.id: nodes[record.id] = None
return True
else:
return False
records = util.map_rows(cursor, {
'id': 'id',
'name': 'name',
'mw': 'mw'
}, record_callback)
# query prices
for node_id in nodes:
# RT price
row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, time, time)).fetchone()
rt5 = row.lmp if row else None
# DA price
row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, hour, hour)).fetchone()
da = row.da_lmp if row else None
# update the hash value
nodes[node_id] = (da, rt5)
# calculate the position pricing
calculate_pnl(records, nodes)
# sort
records.sort(key=lambda r: r.name)
# return the records
return records
</code></pre>
| 3 | 2008-09-22T19:18:21Z | 116,974 | <p>Have you considered using an ORM? <a href="http://www.sqlalchemy.org/features.html" rel="nofollow" title="SQL Alchemy features">SQLAlchemy</a> is pretty good, and <a href="http://elixir.ematia.de/trac/wiki" rel="nofollow" title="Elixir Wiki">Elixir</a> makes it beautiful. It can really reduce the ammount of boilerplate code needed to deal with databases. Also, a lot of the <em>gotchas</em> mentioned have already shown up and the SQLAlchemy developers dealt with them.</p>
| 1 | 2008-09-22T19:30:31Z | [
"python",
"database"
] |
Best practices for manipulating database result sets in Python? | 116,894 | <p>I am writing a simple Python web application that consists of several pages of business data formatted for the iPhone. I'm comfortable programming Python, but I'm not very familiar with Python "idiom," especially regarding classes and objects. Python's object oriented design differs somewhat from other languages I've worked with. So, even though my application is working, I'm curious whether there is a better way to accomplish my goals.</p>
<p>Specifics: How does one typically implement the request-transform-render database workflow in Python? Currently, I am using pyodbc to fetch data, copying the results into attributes on an object, performing some calculations and merges using a list of these objects, then rendering the output from the list of objects. (Sample code below, SQL queries redacted.) Is this sane? Is there a better way? Are there any specific "gotchas" I've stumbled into in my relative ignorance of Python? I'm particularly concerned about how I've implemented the list of rows using the empty "Record" class.</p>
<pre><code>class Record(object):
pass
def calculate_pnl(records, node_prices):
for record in records:
try:
# fill RT and DA prices from the hash retrieved above
if hasattr(record, 'sink') and record.sink:
record.da = node_prices[record.sink][0] - node_prices[record.id][0]
record.rt = node_prices[record.sink][1] - node_prices[record.id][1]
else:
record.da = node_prices[record.id][0]
record.rt = node_prices[record.id][1]
# calculate dependent values: RT-DA and PNL
record.rtda = record.rt - record.da
record.pnl = record.rtda * record.mw
except:
print sys.exc_info()
def map_rows(cursor, mappings, callback=None):
records = []
for row in cursor:
record = Record()
for field, attr in mappings.iteritems():
setattr(record, attr, getattr(row, field, None))
if not callback or callback(record):
records.append(record)
return records
def get_positions(cursor):
# get the latest position time
cursor.execute("SELECT latest data time")
time = cursor.fetchone().time
hour = eelib.util.get_hour_ending(time)
# fetch the current positions
cursor.execute("SELECT stuff FROM atable", (hour))
# read the rows
nodes = {}
def record_callback(record):
if abs(record.mw) > 0:
if record.id: nodes[record.id] = None
return True
else:
return False
records = util.map_rows(cursor, {
'id': 'id',
'name': 'name',
'mw': 'mw'
}, record_callback)
# query prices
for node_id in nodes:
# RT price
row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, time, time)).fetchone()
rt5 = row.lmp if row else None
# DA price
row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, hour, hour)).fetchone()
da = row.da_lmp if row else None
# update the hash value
nodes[node_id] = (da, rt5)
# calculate the position pricing
calculate_pnl(records, nodes)
# sort
records.sort(key=lambda r: r.name)
# return the records
return records
</code></pre>
| 3 | 2008-09-22T19:18:21Z | 117,012 | <p>Using a ORM for an iPhone app might be a bad idea because of performance issues, you want your code to be as fast as possible. So you can't avoid boilerplate code. If you are considering a ORM, besides SQLAlchemy I'd recommend Storm.</p>
| -2 | 2008-09-22T19:35:55Z | [
"python",
"database"
] |
Best practices for manipulating database result sets in Python? | 116,894 | <p>I am writing a simple Python web application that consists of several pages of business data formatted for the iPhone. I'm comfortable programming Python, but I'm not very familiar with Python "idiom," especially regarding classes and objects. Python's object oriented design differs somewhat from other languages I've worked with. So, even though my application is working, I'm curious whether there is a better way to accomplish my goals.</p>
<p>Specifics: How does one typically implement the request-transform-render database workflow in Python? Currently, I am using pyodbc to fetch data, copying the results into attributes on an object, performing some calculations and merges using a list of these objects, then rendering the output from the list of objects. (Sample code below, SQL queries redacted.) Is this sane? Is there a better way? Are there any specific "gotchas" I've stumbled into in my relative ignorance of Python? I'm particularly concerned about how I've implemented the list of rows using the empty "Record" class.</p>
<pre><code>class Record(object):
pass
def calculate_pnl(records, node_prices):
for record in records:
try:
# fill RT and DA prices from the hash retrieved above
if hasattr(record, 'sink') and record.sink:
record.da = node_prices[record.sink][0] - node_prices[record.id][0]
record.rt = node_prices[record.sink][1] - node_prices[record.id][1]
else:
record.da = node_prices[record.id][0]
record.rt = node_prices[record.id][1]
# calculate dependent values: RT-DA and PNL
record.rtda = record.rt - record.da
record.pnl = record.rtda * record.mw
except:
print sys.exc_info()
def map_rows(cursor, mappings, callback=None):
records = []
for row in cursor:
record = Record()
for field, attr in mappings.iteritems():
setattr(record, attr, getattr(row, field, None))
if not callback or callback(record):
records.append(record)
return records
def get_positions(cursor):
# get the latest position time
cursor.execute("SELECT latest data time")
time = cursor.fetchone().time
hour = eelib.util.get_hour_ending(time)
# fetch the current positions
cursor.execute("SELECT stuff FROM atable", (hour))
# read the rows
nodes = {}
def record_callback(record):
if abs(record.mw) > 0:
if record.id: nodes[record.id] = None
return True
else:
return False
records = util.map_rows(cursor, {
'id': 'id',
'name': 'name',
'mw': 'mw'
}, record_callback)
# query prices
for node_id in nodes:
# RT price
row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, time, time)).fetchone()
rt5 = row.lmp if row else None
# DA price
row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, hour, hour)).fetchone()
da = row.da_lmp if row else None
# update the hash value
nodes[node_id] = (da, rt5)
# calculate the position pricing
calculate_pnl(records, nodes)
# sort
records.sort(key=lambda r: r.name)
# return the records
return records
</code></pre>
| 3 | 2008-09-22T19:18:21Z | 117,769 | <p>Depending on how much you want to do with the data you may not need to populate an intermediate object. The cursor's header data structure will let you get the column names - a bit of introspection will let you make a dictionary with col-name:value pairs for the row.
You can pass the dictionary to the % operator. The docs for the odbc module will explain how to get at the column metadata.</p>
<p>This snippet of code to shows the application of the % operator in this manner.</p>
<pre><code>>>> a={'col1': 'foo', 'col2': 'bar', 'col3': 'wibble'}
>>> 'Col1=%(col1)s, Col2=%(col2)s, Col3=%(col3)s' % a
'Col1=foo, Col2=bar, Col3=wibble'
>>>
</code></pre>
| 0 | 2008-09-22T21:30:03Z | [
"python",
"database"
] |
Best practices for manipulating database result sets in Python? | 116,894 | <p>I am writing a simple Python web application that consists of several pages of business data formatted for the iPhone. I'm comfortable programming Python, but I'm not very familiar with Python "idiom," especially regarding classes and objects. Python's object oriented design differs somewhat from other languages I've worked with. So, even though my application is working, I'm curious whether there is a better way to accomplish my goals.</p>
<p>Specifics: How does one typically implement the request-transform-render database workflow in Python? Currently, I am using pyodbc to fetch data, copying the results into attributes on an object, performing some calculations and merges using a list of these objects, then rendering the output from the list of objects. (Sample code below, SQL queries redacted.) Is this sane? Is there a better way? Are there any specific "gotchas" I've stumbled into in my relative ignorance of Python? I'm particularly concerned about how I've implemented the list of rows using the empty "Record" class.</p>
<pre><code>class Record(object):
pass
def calculate_pnl(records, node_prices):
for record in records:
try:
# fill RT and DA prices from the hash retrieved above
if hasattr(record, 'sink') and record.sink:
record.da = node_prices[record.sink][0] - node_prices[record.id][0]
record.rt = node_prices[record.sink][1] - node_prices[record.id][1]
else:
record.da = node_prices[record.id][0]
record.rt = node_prices[record.id][1]
# calculate dependent values: RT-DA and PNL
record.rtda = record.rt - record.da
record.pnl = record.rtda * record.mw
except:
print sys.exc_info()
def map_rows(cursor, mappings, callback=None):
records = []
for row in cursor:
record = Record()
for field, attr in mappings.iteritems():
setattr(record, attr, getattr(row, field, None))
if not callback or callback(record):
records.append(record)
return records
def get_positions(cursor):
# get the latest position time
cursor.execute("SELECT latest data time")
time = cursor.fetchone().time
hour = eelib.util.get_hour_ending(time)
# fetch the current positions
cursor.execute("SELECT stuff FROM atable", (hour))
# read the rows
nodes = {}
def record_callback(record):
if abs(record.mw) > 0:
if record.id: nodes[record.id] = None
return True
else:
return False
records = util.map_rows(cursor, {
'id': 'id',
'name': 'name',
'mw': 'mw'
}, record_callback)
# query prices
for node_id in nodes:
# RT price
row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, time, time)).fetchone()
rt5 = row.lmp if row else None
# DA price
row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, hour, hour)).fetchone()
da = row.da_lmp if row else None
# update the hash value
nodes[node_id] = (da, rt5)
# calculate the position pricing
calculate_pnl(records, nodes)
# sort
records.sort(key=lambda r: r.name)
# return the records
return records
</code></pre>
| 3 | 2008-09-22T19:18:21Z | 117,994 | <p>The empty Record class and the free-floating function that (generally) applies to an individual Record is a hint that you haven't designed your class properly.</p>
<pre><code>class Record( object ):
"""Assuming rtda and pnl must exist."""
def __init__( self ):
self.da= 0
self.rt= 0
self.rtda= 0 # or whatever
self.pnl= None #
self.sink = None # Not clear what this is
def setPnl( self, node_prices ):
# fill RT and DA prices from the hash retrieved above
# calculate dependent values: RT-DA and PNL
</code></pre>
<p>Now, your <code>calculate_pnl( records, node_prices )</code> is simpler and uses the object properly.</p>
<pre><code>def calculate_pnl( records, node_prices ):
for record in records:
record.setPnl( node_prices )
</code></pre>
<p>The point isn't to trivially refactor the code in small ways.</p>
<p>The point is this: <strong>A Class Encapsulates Responsibility</strong>.</p>
<p>Yes, an empty-looking class <em>is</em> usually a problem. It means the responsibilities are scattered somewhere else.</p>
<p>A similar analysis holds for the collection of records. This is more than a simple list, since the collection -- as a whole -- has operations it performs.</p>
<p>The "Request-Transform-Render" isn't quite right. You have a Model (the Record class). Instances of the Model get built (possibly because of a Request.) The Model objects are responsible for their own state transformations and updates. Perhaps they get displayed (or rendered) by some object that examines their state.</p>
<p>It's that "Transform" step that often violates good design by scattering responsibility all over the place. "Transform" is a hold-over from non-object design, where responsibility was a nebulous concept.</p>
| 1 | 2008-09-22T22:23:44Z | [
"python",
"database"
] |
How to Retrieve name of current Windows User (AD or local) using Python? | 117,014 | <p>How can I retrieve the name of the currently logged in user, using a python script? The function should work regardless of whether it is a domain/ad user or a local user.</p>
| 18 | 2008-09-22T19:36:32Z | 117,047 | <p>Try this:</p>
<pre><code>import os;
print os.environ.get( "USERNAME" )
</code></pre>
<p>That should do the job.</p>
| 26 | 2008-09-22T19:42:41Z | [
"python",
"active-directory"
] |
How to Retrieve name of current Windows User (AD or local) using Python? | 117,014 | <p>How can I retrieve the name of the currently logged in user, using a python script? The function should work regardless of whether it is a domain/ad user or a local user.</p>
| 18 | 2008-09-22T19:36:32Z | 117,092 | <p>I don't know Python, but for windows the underlying api is <a href="http://msdn.microsoft.com/en-us/library/ms724435(VS.85).aspx" rel="nofollow">GetUserNameEx</a>, I assume you can call that in Python if os.environ.get( "USERNAME" ) doesn't tell you everything you need to know.</p>
| 1 | 2008-09-22T19:48:00Z | [
"python",
"active-directory"
] |
How to Retrieve name of current Windows User (AD or local) using Python? | 117,014 | <p>How can I retrieve the name of the currently logged in user, using a python script? The function should work regardless of whether it is a domain/ad user or a local user.</p>
| 18 | 2008-09-22T19:36:32Z | 1,992,923 | <pre><code>win32api.GetUserName()
win32api.GetUserNameEx(...)
</code></pre>
<p>See:
<a href="http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html" rel="nofollow">http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html</a></p>
| 2 | 2010-01-02T21:31:16Z | [
"python",
"active-directory"
] |
How to Retrieve name of current Windows User (AD or local) using Python? | 117,014 | <p>How can I retrieve the name of the currently logged in user, using a python script? The function should work regardless of whether it is a domain/ad user or a local user.</p>
| 18 | 2008-09-22T19:36:32Z | 23,963,670 | <p>Pretty old question but to refresh the answer to the original question "How can I retrieve the name of the currently logged in user, using a python script?" use:</p>
<pre><code>import os
print (os.getlogin())
</code></pre>
<p>Per Python documentation: getlogin - Return the name of the user logged in on the controlling terminal of the process.</p>
| 0 | 2014-05-30T21:29:28Z | [
"python",
"active-directory"
] |
How to Retrieve name of current Windows User (AD or local) using Python? | 117,014 | <p>How can I retrieve the name of the currently logged in user, using a python script? The function should work regardless of whether it is a domain/ad user or a local user.</p>
| 18 | 2008-09-22T19:36:32Z | 24,649,918 | <p>as in <a href="http://stackoverflow.com/a/842096/611007">http://stackoverflow.com/a/842096/611007</a> by <a href="http://stackoverflow.com/users/102243/konstantin-tenzin">Konstantin Tenzin</a></p>
<blockquote>
<p>Look at <a href="http://docs.python.org/library/getpass.html" rel="nofollow">getpass</a> module</p>
<pre><code>import getpass
getpass.getuser()
</code></pre>
<p>Availability: Unix, Windows</p>
<p>Note "<em>this function looks at the values of various environment
variables to determine the user name. Therefore, this function should
not be relied on for access control purposes (or possibly any other
purpose, since it allows any user to impersonate any other).</em>"</p>
</blockquote>
<p>at least, definitely preferable over <code>getenv</code>.</p>
| 4 | 2014-07-09T09:25:26Z | [
"python",
"active-directory"
] |
What is the scope for imported classes in python? | 117,127 | <p>Please excuse the vague title. If anyone has a suggestion, please let me know! Also please retag with more appropriate tags!</p>
<p><strong>The Problem</strong></p>
<p>I want to have an instance of an imported class be able to view things in the scope (globals, locals) of the importer. Since I'm not sure of the exact mechanism at work here, I can describe it much better with snippets than words.</p>
<pre><code>## File 1
def f1(): print "go f1!"
class C1(object):
def do_eval(self,x): # maybe this should be do_evil, given what happens
print "evaling"
eval(x)
eval(x,globals(),locals())
</code></pre>
<p>Then run this code from an iteractive session, there there will be lots of <code>NameErrors</code></p>
<pre><code>## interactive
class C2(object):
def do_eval(self,x): # maybe this should be do_evil, given what happens
print "evaling"
eval(x)
eval(x,globals(),locals())
def f2():
print "go f2!"
from file1 import C1
import file1
C1().do_eval('file1.f1()')
C1().do_eval('f1()')
C1().do_eval('f2()')
file1.C1().do_eval('file1.f1()')
file1.C1().do_eval('f1()')
file1.C1().do_eval('f2()')
C2().do_eval('f2()')
C2().do_eval('file1.f1()')
C2().do_eval('f1()')
</code></pre>
<p>Is there a common idiom / pattern for this sort of task? Am I barking up the wrong tree entirely? </p>
| 2 | 2008-09-22T19:52:44Z | 117,174 | <p>Functions are always executed in the scope they are defined in, as are methods and class bodies. They are never executed in another scope. Because importing is just another assignment statement, and everything in Python is a reference, the functions, classes and modules don't even know where they are imported to.</p>
<p>You can do two things: explicitly pass the 'environment' you want them to use, or use stack hackery to access their caller's namespace. The former is vastly preferred over the latter, as it's not as implementation-dependent and fragile as the latter.</p>
<p>You may wish to look at the string.Template class, which tries to do something similar.</p>
| 1 | 2008-09-22T19:58:10Z | [
"python",
"import",
"scope",
"eval"
] |
What is the scope for imported classes in python? | 117,127 | <p>Please excuse the vague title. If anyone has a suggestion, please let me know! Also please retag with more appropriate tags!</p>
<p><strong>The Problem</strong></p>
<p>I want to have an instance of an imported class be able to view things in the scope (globals, locals) of the importer. Since I'm not sure of the exact mechanism at work here, I can describe it much better with snippets than words.</p>
<pre><code>## File 1
def f1(): print "go f1!"
class C1(object):
def do_eval(self,x): # maybe this should be do_evil, given what happens
print "evaling"
eval(x)
eval(x,globals(),locals())
</code></pre>
<p>Then run this code from an iteractive session, there there will be lots of <code>NameErrors</code></p>
<pre><code>## interactive
class C2(object):
def do_eval(self,x): # maybe this should be do_evil, given what happens
print "evaling"
eval(x)
eval(x,globals(),locals())
def f2():
print "go f2!"
from file1 import C1
import file1
C1().do_eval('file1.f1()')
C1().do_eval('f1()')
C1().do_eval('f2()')
file1.C1().do_eval('file1.f1()')
file1.C1().do_eval('f1()')
file1.C1().do_eval('f2()')
C2().do_eval('f2()')
C2().do_eval('file1.f1()')
C2().do_eval('f1()')
</code></pre>
<p>Is there a common idiom / pattern for this sort of task? Am I barking up the wrong tree entirely? </p>
| 2 | 2008-09-22T19:52:44Z | 117,433 | <p>In this example, you can simply hand over functions as objects to the methods in <code>C1</code>:</p>
<pre><code>>>> class C1(object):
>>> def eval(self, x):
>>> x()
>>>
>>> def f2(): print "go f2"
>>> c = C1()
>>> c.eval(f2)
go f2
</code></pre>
<p>In Python, you can pass functions and classes to other methods and invoke/create them there.</p>
<p>If you want to actually evaluate a code string, you have to specify the environment, as already mentioned by Thomas.</p>
<p>Your module from above, slightly changed:</p>
<pre><code>## File 1
def f1(): print "go f1!"
class C1(object):
def do_eval(self, x, e_globals = globals(), e_locals = locals()):
eval(x, e_globals, e_locals)
</code></pre>
<p>Now, in the interactive interpreter:</p>
<pre><code>>>> def f2():
>>> print "go f2!"
>>> from file1 import * # 1
>>> C1().do_eval("f2()") # 2
NameError: name 'f2' is not defined
>>> C1().do_eval("f2()", globals(), locals()) #3
go f2!
>>> C1().do_eval("f1()", globals(), locals()) #4
go f1!
</code></pre>
<h2>Some annotations</h2>
<ol>
<li>Here, we insert all objects from <code>file1</code> into this module's namespace</li>
<li><code>f2</code> is not in the namespace of <code>file1</code>, therefore we get a <code>NameError</code></li>
<li>Now we pass the environment explictly, and the code can be evaluated</li>
<li><code>f1</code> is in the namespace of this module, because we imported it</li>
</ol>
<p><strong>Edit</strong>: Added code sample on how to explicitly pass environment for <code>eval</code>.</p>
| 1 | 2008-09-22T20:32:17Z | [
"python",
"import",
"scope",
"eval"
] |
Python and POST data | 117,167 | <p>In PHP I simply write:</p>
<pre><code>$bob = $_POST['bob'];
</code></pre>
<p>How do I do the same in Python?</p>
<p>And yes, I do normally check that it exists etc, I'm just stripping it down specifically to the functionality I am after.</p>
<p><hr>
Edit: I am not using a framework</p>
| 4 | 2008-09-22T19:57:37Z | 117,201 | <p>The simplest method is the 'cgi' module:</p>
<pre><code>import cgi
data = cgi.FieldStorage()
data['bob']
</code></pre>
<p>But the context you are executing in (frameworks you're using, WSGI or even (heaven forbid) mod_python) may have different, more efficient or more direct methods of access.</p>
| 10 | 2008-09-22T20:01:12Z | [
"python",
"http",
"post"
] |
How to update a Tix.ComboBox's text? | 117,211 | <p>I have a Tix.ComboBox with an editable text field. How do I force the variable holding the value for the text to update?</p>
<p>Let me give a more concrete explanation. I have a combo box and a button. When I click the button, it pops up a message box with the value of the combo box. Let's say the combo box text field currently has the value "thing1". If I type "new" into the box and then click on the button with my mouse, it will pops up the message "thing1". If I type "new" in the box and then tab focus away from the combo box and then click the button the pop up message says "new".</p>
<p>Ho do I force the combo box to update it's value to new without requiring that I tab away from the combo box?</p>
<p>I have included sample code.</p>
<pre><code>import Tix
import tkMessageBox
class App(object):
def __init__(self, window):
window.winfo_toplevel().wm_title("test")
self.window = window
self.combo = Tix.ComboBox(window)
self.combo.insert(Tix.END, 'thing1')
self.combo.insert(Tix.END, 'thing2')
self.combo.entry['state'] = "normal"
self.combo['editable'] = True
self.combo.pack()
button = Tix.Button(window)
button['text'] = "Go"
button['command'] = self.go
button.pack()
def go(self):
tkMessageBox.showinfo('info', self.combo['value'])
if __name__ == '__main__':
root = Tix.Tk()
App(root)
root.mainloop()
</code></pre>
| 2 | 2008-09-22T20:02:38Z | 117,384 | <p>woo!
solved it on my own.</p>
<p>Use </p>
<pre><code>self.combo['selection']
</code></pre>
<p>instead of</p>
<pre><code>self.combo['value']
</code></pre>
| 5 | 2008-09-22T20:24:50Z | [
"python",
"combobox",
"tkinter",
"tix"
] |
How to update a Tix.ComboBox's text? | 117,211 | <p>I have a Tix.ComboBox with an editable text field. How do I force the variable holding the value for the text to update?</p>
<p>Let me give a more concrete explanation. I have a combo box and a button. When I click the button, it pops up a message box with the value of the combo box. Let's say the combo box text field currently has the value "thing1". If I type "new" into the box and then click on the button with my mouse, it will pops up the message "thing1". If I type "new" in the box and then tab focus away from the combo box and then click the button the pop up message says "new".</p>
<p>Ho do I force the combo box to update it's value to new without requiring that I tab away from the combo box?</p>
<p>I have included sample code.</p>
<pre><code>import Tix
import tkMessageBox
class App(object):
def __init__(self, window):
window.winfo_toplevel().wm_title("test")
self.window = window
self.combo = Tix.ComboBox(window)
self.combo.insert(Tix.END, 'thing1')
self.combo.insert(Tix.END, 'thing2')
self.combo.entry['state'] = "normal"
self.combo['editable'] = True
self.combo.pack()
button = Tix.Button(window)
button['text'] = "Go"
button['command'] = self.go
button.pack()
def go(self):
tkMessageBox.showinfo('info', self.combo['value'])
if __name__ == '__main__':
root = Tix.Tk()
App(root)
root.mainloop()
</code></pre>
| 2 | 2008-09-22T20:02:38Z | 207,117 | <p><i>NOTE: copy of Moe's answer that can be selected as chosen answer</i></p>
<p>woo!
solved it on my own.</p>
<p>Use </p>
<pre><code>self.combo['selection']
</code></pre>
<p>instead of</p>
<pre><code>self.combo['value']
</code></pre>
| 1 | 2008-10-16T01:22:20Z | [
"python",
"combobox",
"tkinter",
"tix"
] |
How do I get a decimal value when using the division operator in Python? | 117,250 | <p>For example, the standard division symbol '/' rounds to zero:</p>
<pre><code>>>> 4 / 100
0
</code></pre>
<p>However, I want it to return 0.04. What do I use?</p>
| 31 | 2008-09-22T20:06:16Z | 117,256 | <p>Try 4.0/100</p>
| 1 | 2008-09-22T20:07:20Z | [
"python",
"math",
"syntax",
"operators"
] |
How do I get a decimal value when using the division operator in Python? | 117,250 | <p>For example, the standard division symbol '/' rounds to zero:</p>
<pre><code>>>> 4 / 100
0
</code></pre>
<p>However, I want it to return 0.04. What do I use?</p>
| 31 | 2008-09-22T20:06:16Z | 117,257 | <p>A simple route 4 / 100.0 </p>
<p>or</p>
<p>4.0 / 100</p>
| 1 | 2008-09-22T20:07:27Z | [
"python",
"math",
"syntax",
"operators"
] |
How do I get a decimal value when using the division operator in Python? | 117,250 | <p>For example, the standard division symbol '/' rounds to zero:</p>
<pre><code>>>> 4 / 100
0
</code></pre>
<p>However, I want it to return 0.04. What do I use?</p>
| 31 | 2008-09-22T20:06:16Z | 117,258 | <p>You need to tell Python to use floating point values, not integers. You can do that simply by using a decimal point yourself in the inputs:</p>
<pre><code>>>> 4/100.0
0.040000000000000001
</code></pre>
| 3 | 2008-09-22T20:07:38Z | [
"python",
"math",
"syntax",
"operators"
] |
How do I get a decimal value when using the division operator in Python? | 117,250 | <p>For example, the standard division symbol '/' rounds to zero:</p>
<pre><code>>>> 4 / 100
0
</code></pre>
<p>However, I want it to return 0.04. What do I use?</p>
| 31 | 2008-09-22T20:06:16Z | 117,264 | <p>There are three options:</p>
<pre><code>>>> 4 / float(100)
0.04
>>> 4 / 100.0
0.04
</code></pre>
<p>which is the same behavior as the C, C++, Java etc, or </p>
<pre><code>>>> from __future__ import division
>>> 4 / 100
0.04
</code></pre>
<p>You can also activate this behavior by passing the argument <code>-Qnew</code> to the Python interpreter:</p>
<pre><code>$ python -Qnew
>>> 4 / 100
0.04
</code></pre>
<p>The second option will be the default in Python 3.0. If you want to have the old integer division, you have to use the <code>//</code> operator. </p>
<p><strong>Edit</strong>: added section about <code>-Qnew</code>, thanks to <a href="http://stackoverflow.com/users/6899/">ΤÎΩΤÎÎÎÎ¥</a>!</p>
| 79 | 2008-09-22T20:08:15Z | [
"python",
"math",
"syntax",
"operators"
] |
How do I get a decimal value when using the division operator in Python? | 117,250 | <p>For example, the standard division symbol '/' rounds to zero:</p>
<pre><code>>>> 4 / 100
0
</code></pre>
<p>However, I want it to return 0.04. What do I use?</p>
| 31 | 2008-09-22T20:06:16Z | 117,270 | <p>Make one or both of the terms a floating point number, like so:</p>
<pre><code>4.0/100.0
</code></pre>
<p>Alternatively, turn on the feature that will be default in Python 3.0, 'true division', that does what you want. At the top of your module or script, do:</p>
<pre><code>from __future__ import division
</code></pre>
| 7 | 2008-09-22T20:08:45Z | [
"python",
"math",
"syntax",
"operators"
] |
How do I get a decimal value when using the division operator in Python? | 117,250 | <p>For example, the standard division symbol '/' rounds to zero:</p>
<pre><code>>>> 4 / 100
0
</code></pre>
<p>However, I want it to return 0.04. What do I use?</p>
| 31 | 2008-09-22T20:06:16Z | 117,285 | <p>You cant get a decimal value by dividing one integer with another, you'll allways get an integer that way (result truncated to integer). You need at least one value to be a decimal number.</p>
| 0 | 2008-09-22T20:11:02Z | [
"python",
"math",
"syntax",
"operators"
] |
How do I get a decimal value when using the division operator in Python? | 117,250 | <p>For example, the standard division symbol '/' rounds to zero:</p>
<pre><code>>>> 4 / 100
0
</code></pre>
<p>However, I want it to return 0.04. What do I use?</p>
| 31 | 2008-09-22T20:06:16Z | 117,682 | <p>Other answers suggest how to get a floating-point value. While this wlil be close to what you want, it won't be exact:</p>
<pre><code>>>> 0.4/100.
0.0040000000000000001
</code></pre>
<p>If you actually want a <em>decimal</em> value, do this:</p>
<pre><code>>>> import decimal
>>> decimal.Decimal('4') / decimal.Decimal('100')
Decimal("0.04")
</code></pre>
<p>That will give you an object that properly knows that 4 / 100 in <em>base 10</em> is "0.04". Floating-point numbers are actually in base 2, i.e. binary, not decimal.</p>
| 21 | 2008-09-22T21:12:07Z | [
"python",
"math",
"syntax",
"operators"
] |
How do I get a decimal value when using the division operator in Python? | 117,250 | <p>For example, the standard division symbol '/' rounds to zero:</p>
<pre><code>>>> 4 / 100
0
</code></pre>
<p>However, I want it to return 0.04. What do I use?</p>
| 31 | 2008-09-22T20:06:16Z | 117,806 | <p>You might want to look at Python's <a href="http://docs.python.org/lib/module-decimal.html" rel="nofollow">decimal</a> package, also. This will provide nice decimal results.</p>
<pre><code>>>> decimal.Decimal('4')/100
Decimal("0.04")
</code></pre>
| 2 | 2008-09-22T21:38:16Z | [
"python",
"math",
"syntax",
"operators"
] |
How do I get a decimal value when using the division operator in Python? | 117,250 | <p>For example, the standard division symbol '/' rounds to zero:</p>
<pre><code>>>> 4 / 100
0
</code></pre>
<p>However, I want it to return 0.04. What do I use?</p>
| 31 | 2008-09-22T20:06:16Z | 30,474,510 | <p>Please consider following example</p>
<pre><code>float tot=(float)31/7;
</code></pre>
| -1 | 2015-05-27T06:16:16Z | [
"python",
"math",
"syntax",
"operators"
] |
What's the Name of the Python Module that Formats arbitrary Text to nicely looking HTML? | 117,477 | <p>A while ago I came across a Python library that formats regular text to HTML similar to Markdown, reStructuredText and Textile, just that it had no syntax at all. It detected indentatations, quotes, links and newlines/paragraphs only.</p>
<p>Unfortunately I lost the name of the library and was unable to Google it. Anyone any ideas?</p>
<p><strong>Edit:</strong> reStructuredText aka rst == docutils. That's not what I'm looking for :)</p>
| 10 | 2008-09-22T20:39:11Z | 117,543 | <p><a href="http://sphinx.pocoo.org/" rel="nofollow">Sphinx</a> is a documentation generator using reStructuredText. It's quite nice, although I haven't used it personally.</p>
<p>The website <a href="http://sphinx.pocoo.org/" rel="nofollow">Hazel Tree</a>, which compiles python text uses Sphinx, and so does the new Python documentation.</p>
| 0 | 2008-09-22T20:48:51Z | [
"python",
"formatting",
"markup"
] |
What's the Name of the Python Module that Formats arbitrary Text to nicely looking HTML? | 117,477 | <p>A while ago I came across a Python library that formats regular text to HTML similar to Markdown, reStructuredText and Textile, just that it had no syntax at all. It detected indentatations, quotes, links and newlines/paragraphs only.</p>
<p>Unfortunately I lost the name of the library and was unable to Google it. Anyone any ideas?</p>
<p><strong>Edit:</strong> reStructuredText aka rst == docutils. That's not what I'm looking for :)</p>
| 10 | 2008-09-22T20:39:11Z | 117,819 | <p><p><a href="http://www.freewisdom.org/projects/python-markdown/" rel="nofollow">Markdown in python</a> is a python implementation of the <a href="http://daringfireball.net/projects/markdown/" rel="nofollow">perl based markdown</a> utility.</p>
<p><p>Markown converts various forms of structured text to valid html, and one of the supported forms is just plain ascii. Use is pretty <a href="http://www.freewisdom.org/projects/python-markdown/Command_Line" rel="nofollow">straight forward</a>.</p>
<pre><code>python markdown.py input_file.txt > output_file.html
</code></pre>
<p>Markdown can be easily <a href="http://www.freewisdom.org/projects/python-markdown/Using_as_a_Module" rel="nofollow">called as a module</a> too:</p>
<pre><code>import markdown
html = markdown.markdown(your_text_string)
</code></pre>
| 1 | 2008-09-22T21:40:15Z | [
"python",
"formatting",
"markup"
] |
What's the Name of the Python Module that Formats arbitrary Text to nicely looking HTML? | 117,477 | <p>A while ago I came across a Python library that formats regular text to HTML similar to Markdown, reStructuredText and Textile, just that it had no syntax at all. It detected indentatations, quotes, links and newlines/paragraphs only.</p>
<p>Unfortunately I lost the name of the library and was unable to Google it. Anyone any ideas?</p>
<p><strong>Edit:</strong> reStructuredText aka rst == docutils. That's not what I'm looking for :)</p>
| 10 | 2008-09-22T20:39:11Z | 117,824 | <p>Okay. I found it now. It's called <a href="http://glyphobet.net/pottymouth/">PottyMouth</a>.</p>
| 14 | 2008-09-22T21:41:26Z | [
"python",
"formatting",
"markup"
] |
How do I use timezones with a datetime object in python? | 117,514 | <p>How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone()</p>
<pre><code>import datetime, re
from datetime import tzinfo
class myTimeZone(tzinfo):
"""docstring for myTimeZone"""
def utfoffset(self, dt):
return timedelta(hours=1)
def myDateHandler(aDateString):
"""u'Sat, 6 Sep 2008 21:16:33 EDT'"""
_my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)')
day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups()
month = [
'JAN', 'FEB', 'MAR',
'APR', 'MAY', 'JUN',
'JUL', 'AUG', 'SEP',
'OCT', 'NOV', 'DEC'
].index(month.upper()) + 1
dt = datetime.datetime(
int(year), int(month), int(day),
int(hour), int(minute), int(second)
)
# dt = dt - datetime.timedelta(hours=1)
# dt = dt - dt.tzinfo.utfoffset(myTimeZone())
return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0)
def main():
print myDateHandler("Sat, 6 Sep 2008 21:16:33 EDT")
if __name__ == '__main__':
main()
</code></pre>
| 37 | 2008-09-22T20:44:39Z | 117,523 | <p>The Python standard library doesn't contain timezone information, because unfortunately timezone data changes a lot faster than Python. You need a third-party module for this; the usual choice is <a href="http://pytz.sourceforge.net">pytz</a></p>
| 9 | 2008-09-22T20:46:08Z | [
"python",
"datetime",
"timezone"
] |
How do I use timezones with a datetime object in python? | 117,514 | <p>How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone()</p>
<pre><code>import datetime, re
from datetime import tzinfo
class myTimeZone(tzinfo):
"""docstring for myTimeZone"""
def utfoffset(self, dt):
return timedelta(hours=1)
def myDateHandler(aDateString):
"""u'Sat, 6 Sep 2008 21:16:33 EDT'"""
_my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)')
day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups()
month = [
'JAN', 'FEB', 'MAR',
'APR', 'MAY', 'JUN',
'JUL', 'AUG', 'SEP',
'OCT', 'NOV', 'DEC'
].index(month.upper()) + 1
dt = datetime.datetime(
int(year), int(month), int(day),
int(hour), int(minute), int(second)
)
# dt = dt - datetime.timedelta(hours=1)
# dt = dt - dt.tzinfo.utfoffset(myTimeZone())
return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0)
def main():
print myDateHandler("Sat, 6 Sep 2008 21:16:33 EDT")
if __name__ == '__main__':
main()
</code></pre>
| 37 | 2008-09-22T20:44:39Z | 117,615 | <p>I recommend <code>babel</code> and <code>pytz</code> when working with timezones. Keep your internal datetime objects naive and in UTC and convert to your timezone for formatting only. The reason why you probably want naive objects (objects without timezone information) is that many libraries and database adapters have no idea about timezones.</p>
<ul>
<li><a href="http://babel.pocoo.org/">Babel</a></li>
<li><a href="http://pytz.sourceforge.net/">pytz</a></li>
</ul>
| 36 | 2008-09-22T20:59:40Z | [
"python",
"datetime",
"timezone"
] |
How do I use timezones with a datetime object in python? | 117,514 | <p>How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone()</p>
<pre><code>import datetime, re
from datetime import tzinfo
class myTimeZone(tzinfo):
"""docstring for myTimeZone"""
def utfoffset(self, dt):
return timedelta(hours=1)
def myDateHandler(aDateString):
"""u'Sat, 6 Sep 2008 21:16:33 EDT'"""
_my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)')
day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups()
month = [
'JAN', 'FEB', 'MAR',
'APR', 'MAY', 'JUN',
'JUL', 'AUG', 'SEP',
'OCT', 'NOV', 'DEC'
].index(month.upper()) + 1
dt = datetime.datetime(
int(year), int(month), int(day),
int(hour), int(minute), int(second)
)
# dt = dt - datetime.timedelta(hours=1)
# dt = dt - dt.tzinfo.utfoffset(myTimeZone())
return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0)
def main():
print myDateHandler("Sat, 6 Sep 2008 21:16:33 EDT")
if __name__ == '__main__':
main()
</code></pre>
| 37 | 2008-09-22T20:44:39Z | 1,893,437 | <p>For the current local timezone, you can you use:</p>
<pre><code>>>> import time
>>> offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone
>>> offset / 60 / 60 * -1
-9
</code></pre>
<p>The value returned is in seconds West of UTC (with areas East of UTC getting a negative value). This is the opposite to how we'd actually like it, hence the <code>* -1</code>.</p>
<p><code>localtime().tm_isdst</code> will be zero if daylight savings is currently not in effect (although this may not be correct if an area has recently changed their daylight savings law).</p>
| 7 | 2009-12-12T13:35:12Z | [
"python",
"datetime",
"timezone"
] |
How do I use timezones with a datetime object in python? | 117,514 | <p>How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone()</p>
<pre><code>import datetime, re
from datetime import tzinfo
class myTimeZone(tzinfo):
"""docstring for myTimeZone"""
def utfoffset(self, dt):
return timedelta(hours=1)
def myDateHandler(aDateString):
"""u'Sat, 6 Sep 2008 21:16:33 EDT'"""
_my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)')
day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups()
month = [
'JAN', 'FEB', 'MAR',
'APR', 'MAY', 'JUN',
'JUL', 'AUG', 'SEP',
'OCT', 'NOV', 'DEC'
].index(month.upper()) + 1
dt = datetime.datetime(
int(year), int(month), int(day),
int(hour), int(minute), int(second)
)
# dt = dt - datetime.timedelta(hours=1)
# dt = dt - dt.tzinfo.utfoffset(myTimeZone())
return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0)
def main():
print myDateHandler("Sat, 6 Sep 2008 21:16:33 EDT")
if __name__ == '__main__':
main()
</code></pre>
| 37 | 2008-09-22T20:44:39Z | 10,484,336 | <p>We are familiar to timezone cut off from GMT (now UTC), but Python takes timezone cut off from Western. That's why there are negative timezone cutoff's in Python, I believe.</p>
| -1 | 2012-05-07T15:00:07Z | [
"python",
"datetime",
"timezone"
] |
Can you do LINQ-like queries in a language like Python or Boo? | 117,732 | <p>Take this simple C# LINQ query, and imagine that 'db.Numbers' is an SQL table with one column, Number:</p>
<p>var result =
from n in db.Numbers
where n.Number < 5
select n.Number;</p>
<p>This will run very efficiently in C#, because it generates an SQL query something like "select Number from Numbers where Number < 5". What it <em>doesn't</em> do is select <em>all</em> the numbers from the database, and then filter them in C#, as it might appear to do at first.</p>
<p>Python supports a similar syntax:</p>
<p>result = [n.Number for n in Numbers if n.Number < 5]</p>
<p>But it the "if" clause here does the filtering on the client side, rather than the server side, which is much less efficient.</p>
<p>Is there something as efficient as LINQ in Python? (I'm currently evaluating Python vs. IronPython vs. Boo, so an answer that works in any of those languages is fine.)</p>
| 4 | 2008-09-22T21:24:00Z | 117,794 | <p>Look closely at <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>. This can probably do much of what you want. It gives you Python syntax for plain-old SQL that runs on the server.</p>
| 5 | 2008-09-22T21:35:01Z | [
"python",
"linq",
"linq-to-sql",
"ironpython",
"boo"
] |
Can you do LINQ-like queries in a language like Python or Boo? | 117,732 | <p>Take this simple C# LINQ query, and imagine that 'db.Numbers' is an SQL table with one column, Number:</p>
<p>var result =
from n in db.Numbers
where n.Number < 5
select n.Number;</p>
<p>This will run very efficiently in C#, because it generates an SQL query something like "select Number from Numbers where Number < 5". What it <em>doesn't</em> do is select <em>all</em> the numbers from the database, and then filter them in C#, as it might appear to do at first.</p>
<p>Python supports a similar syntax:</p>
<p>result = [n.Number for n in Numbers if n.Number < 5]</p>
<p>But it the "if" clause here does the filtering on the client side, rather than the server side, which is much less efficient.</p>
<p>Is there something as efficient as LINQ in Python? (I'm currently evaluating Python vs. IronPython vs. Boo, so an answer that works in any of those languages is fine.)</p>
| 4 | 2008-09-22T21:24:00Z | 117,818 | <p>LINQ is a language feature of C# and VB.NET. It is a special syntax recognized by the compiler and treated specially. It is also dependent on another language feature called expression trees.</p>
<p>Expression trees are a <strong>little</strong> different in that they are not special syntax. They are written just like any other class instantiation, but the compiler does treat them specially under the covers by turning a lambda into an instantiation of a run-time <a href="http://en.wikipedia.org/wiki/Abstract_syntax_tree">abstract syntax tree</a>. These can be manipulated at run-time to produce a command in another language (i.e. SQL).</p>
<p>The C# and VB.NET compilers take LINQ syntax, and turn it into lambdas, then pass those into expression tree instantiations. Then there are a bunch of framework classes that manipulate these trees to produce SQL. You can also find other libraries, both MS-produced and third party, that offer "LINQ providers", which basically pop a different AST processer in to produce something from the LINQ other than SQL.</p>
<p>So one obstacle to doing these things in another language is the question whether they support run-time AST building/manipulation. I don't know whether any implementations of Python or Boo do, but I haven't heard of any such features.</p>
| 5 | 2008-09-22T21:40:10Z | [
"python",
"linq",
"linq-to-sql",
"ironpython",
"boo"
] |
Can you do LINQ-like queries in a language like Python or Boo? | 117,732 | <p>Take this simple C# LINQ query, and imagine that 'db.Numbers' is an SQL table with one column, Number:</p>
<p>var result =
from n in db.Numbers
where n.Number < 5
select n.Number;</p>
<p>This will run very efficiently in C#, because it generates an SQL query something like "select Number from Numbers where Number < 5". What it <em>doesn't</em> do is select <em>all</em> the numbers from the database, and then filter them in C#, as it might appear to do at first.</p>
<p>Python supports a similar syntax:</p>
<p>result = [n.Number for n in Numbers if n.Number < 5]</p>
<p>But it the "if" clause here does the filtering on the client side, rather than the server side, which is much less efficient.</p>
<p>Is there something as efficient as LINQ in Python? (I'm currently evaluating Python vs. IronPython vs. Boo, so an answer that works in any of those languages is fine.)</p>
| 4 | 2008-09-22T21:24:00Z | 118,350 | <p>I believe that when IronPython 2.0 is complete, it will have LINQ support (see <a href="http://groups.google.com/group/ironpy/browse_thread/thread/eb6b9eb2241cc68e" rel="nofollow">this thread</a> for some example discussion). Right now you should be able to write something like:</p>
<pre><code>Queryable.Select(Queryable.Where(someInputSequence, somePredicate), someFuncThatReturnsTheSequenceElement)
</code></pre>
<p>Something better might have made it into IronPython 2.0b4 - there's a lot of <a href="http://ironpython-urls.blogspot.com/2008/09/dlr-namespace-change-fire-drill.html" rel="nofollow">current discussion</a> about how naming conflicts were handled.</p>
| 4 | 2008-09-23T00:11:39Z | [
"python",
"linq",
"linq-to-sql",
"ironpython",
"boo"
] |
Can you do LINQ-like queries in a language like Python or Boo? | 117,732 | <p>Take this simple C# LINQ query, and imagine that 'db.Numbers' is an SQL table with one column, Number:</p>
<p>var result =
from n in db.Numbers
where n.Number < 5
select n.Number;</p>
<p>This will run very efficiently in C#, because it generates an SQL query something like "select Number from Numbers where Number < 5". What it <em>doesn't</em> do is select <em>all</em> the numbers from the database, and then filter them in C#, as it might appear to do at first.</p>
<p>Python supports a similar syntax:</p>
<p>result = [n.Number for n in Numbers if n.Number < 5]</p>
<p>But it the "if" clause here does the filtering on the client side, rather than the server side, which is much less efficient.</p>
<p>Is there something as efficient as LINQ in Python? (I'm currently evaluating Python vs. IronPython vs. Boo, so an answer that works in any of those languages is fine.)</p>
| 4 | 2008-09-22T21:24:00Z | 118,496 | <p><a href="http://www.sqlalchemy.org/trac/wiki/SqlSoup" rel="nofollow">sqlsoup</a> in sqlalchemy gives you the quickest solution in python I think if you want a clear(ish) one liner . Look at the page to see.</p>
<p>It should be something like...</p>
<pre><code>result = [n.Number for n in db.Numbers.filter(db.Numbers.Number < 5).all()]
</code></pre>
| 6 | 2008-09-23T00:52:48Z | [
"python",
"linq",
"linq-to-sql",
"ironpython",
"boo"
] |
Can you do LINQ-like queries in a language like Python or Boo? | 117,732 | <p>Take this simple C# LINQ query, and imagine that 'db.Numbers' is an SQL table with one column, Number:</p>
<p>var result =
from n in db.Numbers
where n.Number < 5
select n.Number;</p>
<p>This will run very efficiently in C#, because it generates an SQL query something like "select Number from Numbers where Number < 5". What it <em>doesn't</em> do is select <em>all</em> the numbers from the database, and then filter them in C#, as it might appear to do at first.</p>
<p>Python supports a similar syntax:</p>
<p>result = [n.Number for n in Numbers if n.Number < 5]</p>
<p>But it the "if" clause here does the filtering on the client side, rather than the server side, which is much less efficient.</p>
<p>Is there something as efficient as LINQ in Python? (I'm currently evaluating Python vs. IronPython vs. Boo, so an answer that works in any of those languages is fine.)</p>
| 4 | 2008-09-22T21:24:00Z | 235,727 | <p>A key factor for LINQ is the ability of the compiler to generate expression trees.
I am using a macro in Nemerle that converts a given Nemerle expression into an Expression tree object.
I can then pass this to the Where/Select/etc extension methods on IQueryables.
It's not quite the syntax of C# and VB, but it's close enough for me. </p>
<p>I got the Nemerle macro via a link on this post:
<a href="http://groups.google.com/group/nemerle-dev/browse_thread/thread/99b9dcfe204a578e" rel="nofollow">http://groups.google.com/group/nemerle-dev/browse_thread/thread/99b9dcfe204a578e</a></p>
<p>It should be possible to create a similar macro for Boo. It's quite a bit of work however, given the large set of possible expressions you need to support.
Ayende has given a proof of concept here:
<a href="http://ayende.com/Blog/archive/2008/08/05/Ugly-Linq.aspx" rel="nofollow">http://ayende.com/Blog/archive/2008/08/05/Ugly-Linq.aspx</a></p>
| 1 | 2008-10-25T01:12:45Z | [
"python",
"linq",
"linq-to-sql",
"ironpython",
"boo"
] |
Can you do LINQ-like queries in a language like Python or Boo? | 117,732 | <p>Take this simple C# LINQ query, and imagine that 'db.Numbers' is an SQL table with one column, Number:</p>
<p>var result =
from n in db.Numbers
where n.Number < 5
select n.Number;</p>
<p>This will run very efficiently in C#, because it generates an SQL query something like "select Number from Numbers where Number < 5". What it <em>doesn't</em> do is select <em>all</em> the numbers from the database, and then filter them in C#, as it might appear to do at first.</p>
<p>Python supports a similar syntax:</p>
<p>result = [n.Number for n in Numbers if n.Number < 5]</p>
<p>But it the "if" clause here does the filtering on the client side, rather than the server side, which is much less efficient.</p>
<p>Is there something as efficient as LINQ in Python? (I'm currently evaluating Python vs. IronPython vs. Boo, so an answer that works in any of those languages is fine.)</p>
| 4 | 2008-09-22T21:24:00Z | 254,524 | <p>Boo supports list generator expressions using the same syntax as python. For more information on that, check out the Boo documentation on <a href="http://boo.codehaus.org/Generator+Expressions" rel="nofollow">Generator expressions</a> and <a href="http://boo.codehaus.org/List+Generators" rel="nofollow">List comprehensions</a>.</p>
| 1 | 2008-10-31T18:55:58Z | [
"python",
"linq",
"linq-to-sql",
"ironpython",
"boo"
] |
Debug/Monitor middleware for python wsgi applications | 117,986 | <p>I'm searching a wsgi middleware which I can warp around a wsgi applications and which lets me monitor incoming and outgoing http requests and header fields.</p>
<p>Something like firefox live headers, but for the server side.</p>
| 1 | 2008-09-22T22:22:18Z | 118,037 | <p>That shouldn't be too hard to write yourself as long as you only need the headers. Try that:</p>
<pre><code>import sys
def log_headers(app, stream=None):
if stream is None:
stream = sys.stdout
def proxy(environ, start_response):
for key, value in environ.iteritems():
if key.startswith('HTTP_'):
stream.write('%s: %s\n' % (key[5:].title().replace('_', '-'), value))
return app(environ, start_response)
return proxy
</code></pre>
| 2 | 2008-09-22T22:35:22Z | [
"python",
"debugging",
"wsgi",
"middleware"
] |
Debug/Monitor middleware for python wsgi applications | 117,986 | <p>I'm searching a wsgi middleware which I can warp around a wsgi applications and which lets me monitor incoming and outgoing http requests and header fields.</p>
<p>Something like firefox live headers, but for the server side.</p>
| 1 | 2008-09-22T22:22:18Z | 118,142 | <p>The middleware</p>
<pre><code>from wsgiref.util import request_uri
import sys
def logging_middleware(application, stream=sys.stdout):
def _logger(environ, start_response):
stream.write('REQUEST\n')
stream.write('%s %s\n' %(
environ['REQUEST_METHOD'],
request_uri(environ),
))
for name, value in environ.items():
if name.startswith('HTTP_'):
stream.write(' %s: %s\n' %(
name[5:].title().replace('_', '-'),
value,
))
stream.flush()
def _start_response(code, headers):
stream.write('RESPONSE\n')
stream.write('%s\n' % code)
for data in headers:
stream.write(' %s: %s\n' % data)
stream.flush()
start_response(code, headers)
return application(environ, _start_response)
return _logger
</code></pre>
<p>The test</p>
<pre><code>def application(environ, start_response):
start_response('200 OK', [
('Content-Type', 'text/html')
])
return ['Hello World']
if __name__ == '__main__':
logger = logging_middleware(application)
from wsgiref.simple_server import make_server
httpd = make_server('', 1234, logger)
httpd.serve_forever()
</code></pre>
<p>See also the <a href="http://werkzeug.pocoo.org/documentation/debug" rel="nofollow">werkzeug debugger</a> Armin wrote, it's usefull for interactive debugging.</p>
| 2 | 2008-09-22T23:05:34Z | [
"python",
"debugging",
"wsgi",
"middleware"
] |
Debug/Monitor middleware for python wsgi applications | 117,986 | <p>I'm searching a wsgi middleware which I can warp around a wsgi applications and which lets me monitor incoming and outgoing http requests and header fields.</p>
<p>Something like firefox live headers, but for the server side.</p>
| 1 | 2008-09-22T22:22:18Z | 307,547 | <p>If you want Apache-style logs, try <a href="http://svn.pythonpaste.org/Paste/trunk/paste/translogger.py" rel="nofollow">paste.translogger</a></p>
<p>But for something more complete, though not in a very handy or stable location (maybe copy it into your source) is <a href="http://svn.pythonpaste.org/Paste/WSGIFilter/trunk/wsgifilter/proxyapp.py" rel="nofollow">wsgifilter.proxyapp.DebugHeaders</a></p>
<p>And writing one using <a href="http://pythonpaste.org/webob" rel="nofollow">WebOb</a>:</p>
<pre><code>import webob, sys
class LogHeaders(object):
def __init__(self, app, stream=sys.stderr):
self.app = app
self.stream = stream
def __call__(self, environ, start_response):
req = webob.Request(environ)
resp = req.get_response(self.app)
print >> self.stream, 'Request:\n%s\n\nResponse:\n%s\n\n\n' % (req, resp)
return resp(environ, start_response)
</code></pre>
| 2 | 2008-11-21T01:35:12Z | [
"python",
"debugging",
"wsgi",
"middleware"
] |
Debug/Monitor middleware for python wsgi applications | 117,986 | <p>I'm searching a wsgi middleware which I can warp around a wsgi applications and which lets me monitor incoming and outgoing http requests and header fields.</p>
<p>Something like firefox live headers, but for the server side.</p>
| 1 | 2008-09-22T22:22:18Z | 1,041,821 | <p>The mod_wsgi documentation provides various tips on debugging which are applicable to any WSGI hosting mechanism and not just mod_wsgi. See:</p>
<p><a href="http://code.google.com/p/modwsgi/wiki/DebuggingTechniques" rel="nofollow">http://code.google.com/p/modwsgi/wiki/DebuggingTechniques</a></p>
<p>This includes an example WSGI middleware that captures request and response.</p>
| 1 | 2009-06-25T01:53:10Z | [
"python",
"debugging",
"wsgi",
"middleware"
] |
Debug/Monitor middleware for python wsgi applications | 117,986 | <p>I'm searching a wsgi middleware which I can warp around a wsgi applications and which lets me monitor incoming and outgoing http requests and header fields.</p>
<p>Something like firefox live headers, but for the server side.</p>
| 1 | 2008-09-22T22:22:18Z | 2,384,940 | <p>My WebCore project has a bit of middleware that logs the entire WSGI environment (thus Beaker sessions, headers, etc.) for the incoming request, headers for outbound responses, as well as performance information to a MongoDB database. Average overhead is around 4ms.</p>
<p>The module has been removed from the core package, but hasnât yet been integrated into its own. The current version as of this answer is available in the Git history:</p>
<p><a href="http://github.com/GothAlice/WebCore/blob/cd1d6dcbd081323869968c51a78eceb1a32007d8/web/extras/cprofile.py" rel="nofollow">http://github.com/GothAlice/WebCore/blob/cd1d6dcbd081323869968c51a78eceb1a32007d8/web/extras/cprofile.py</a></p>
| 1 | 2010-03-05T06:23:26Z | [
"python",
"debugging",
"wsgi",
"middleware"
] |
How can i parse a comma delimited string into a list (caveat)? | 118,096 | <p>I need to be able to take a string like:</p>
<pre><code>'''foo, bar, "one, two", three four'''
</code></pre>
<p>into:</p>
<pre><code>['foo', 'bar', 'one, two', 'three four']
</code></pre>
<p>I have an feeling (with hints from #python) that the solution is going to involve the shlex module.</p>
| 19 | 2008-09-22T22:54:10Z | 118,110 | <p>You may also want to consider the <a href="http://docs.python.org/lib/module-csv.html" rel="nofollow">csv</a> module. I haven't tried it, but it looks like your input data is closer to CSV than to shell syntax (which is what shlex parses).</p>
| 5 | 2008-09-22T22:56:56Z | [
"python",
"split",
"escaping",
"quotes"
] |
How can i parse a comma delimited string into a list (caveat)? | 118,096 | <p>I need to be able to take a string like:</p>
<pre><code>'''foo, bar, "one, two", three four'''
</code></pre>
<p>into:</p>
<pre><code>['foo', 'bar', 'one, two', 'three four']
</code></pre>
<p>I have an feeling (with hints from #python) that the solution is going to involve the shlex module.</p>
| 19 | 2008-09-22T22:54:10Z | 118,132 | <p>You could do something like this:</p>
<pre><code>>>> import re
>>> pattern = re.compile(r'\s*("[^"]*"|.*?)\s*,')
>>> def split(line):
... return [x[1:-1] if x[:1] == x[-1:] == '"' else x
... for x in pattern.findall(line.rstrip(',') + ',')]
...
>>> split("foo, bar, baz")
['foo', 'bar', 'baz']
>>> split('foo, bar, baz, "blub blah"')
['foo', 'bar', 'baz', 'blub blah']
</code></pre>
| 1 | 2008-09-22T23:02:31Z | [
"python",
"split",
"escaping",
"quotes"
] |
How can i parse a comma delimited string into a list (caveat)? | 118,096 | <p>I need to be able to take a string like:</p>
<pre><code>'''foo, bar, "one, two", three four'''
</code></pre>
<p>into:</p>
<pre><code>['foo', 'bar', 'one, two', 'three four']
</code></pre>
<p>I have an feeling (with hints from #python) that the solution is going to involve the shlex module.</p>
| 19 | 2008-09-22T22:54:10Z | 118,161 | <p>If it doesn't need to be pretty, this might get you on your way:</p>
<pre><code>def f(s, splitifeven):
if splitifeven & 1:
return [s]
return [x.strip() for x in s.split(",") if x.strip() != '']
ss = 'foo, bar, "one, two", three four'
print sum([f(s, sie) for sie, s in enumerate(ss.split('"'))], [])
</code></pre>
| -2 | 2008-09-22T23:09:25Z | [
"python",
"split",
"escaping",
"quotes"
] |
How can i parse a comma delimited string into a list (caveat)? | 118,096 | <p>I need to be able to take a string like:</p>
<pre><code>'''foo, bar, "one, two", three four'''
</code></pre>
<p>into:</p>
<pre><code>['foo', 'bar', 'one, two', 'three four']
</code></pre>
<p>I have an feeling (with hints from #python) that the solution is going to involve the shlex module.</p>
| 19 | 2008-09-22T22:54:10Z | 118,162 | <p>It depends how complicated you want to get... do you want to allow more than one type of quoting. How about escaped quotes?</p>
<p>Your syntax looks very much like the common CSV file format, which is supported by the Python standard library:</p>
<pre><code>import csv
reader = csv.reader(['''foo, bar, "one, two", three four'''], skipinitialspace=True)
for r in reader:
print r
</code></pre>
<p>Outputs:</p>
<pre><code>['foo', 'bar', 'one, two', 'three four']
</code></pre>
<p>HTH!</p>
| 39 | 2008-09-22T23:09:45Z | [
"python",
"split",
"escaping",
"quotes"
] |
How can i parse a comma delimited string into a list (caveat)? | 118,096 | <p>I need to be able to take a string like:</p>
<pre><code>'''foo, bar, "one, two", three four'''
</code></pre>
<p>into:</p>
<pre><code>['foo', 'bar', 'one, two', 'three four']
</code></pre>
<p>I have an feeling (with hints from #python) that the solution is going to involve the shlex module.</p>
| 19 | 2008-09-22T22:54:10Z | 118,187 | <p>The shlex module solution allows escaped quotes, one quote escape another, and all fancy stuff shell supports.</p>
<pre><code>>>> import shlex
>>> my_splitter = shlex.shlex('''foo, bar, "one, two", three four''', posix=True)
>>> my_splitter.whitespace += ','
>>> my_splitter.whitespace_split = True
>>> print list(my_splitter)
['foo', 'bar', 'one, two', 'three', 'four']
</code></pre>
<p>escaped quotes example:</p>
<pre><code>>>> my_splitter = shlex.shlex('''"test, a",'foo,bar",baz',bar \xc3\xa4 baz''',
posix=True)
>>> my_splitter.whitespace = ',' ; my_splitter.whitespace_split = True
>>> print list(my_splitter)
['test, a', 'foo,bar",baz', 'bar \xc3\xa4 baz']
</code></pre>
| 21 | 2008-09-22T23:15:45Z | [
"python",
"split",
"escaping",
"quotes"
] |
How can i parse a comma delimited string into a list (caveat)? | 118,096 | <p>I need to be able to take a string like:</p>
<pre><code>'''foo, bar, "one, two", three four'''
</code></pre>
<p>into:</p>
<pre><code>['foo', 'bar', 'one, two', 'three four']
</code></pre>
<p>I have an feeling (with hints from #python) that the solution is going to involve the shlex module.</p>
| 19 | 2008-09-22T22:54:10Z | 157,771 | <p>I'd say a regular expression would be what you're looking for here, though I'm not terribly familiar with Python's Regex engine.</p>
<p>Assuming you use lazy matches, you can get a set of matches on a string which you can put into your array.</p>
| 0 | 2008-10-01T14:08:53Z | [
"python",
"split",
"escaping",
"quotes"
] |
How do I develop and create a self-contained PyGTK application bundle for MacOS, with native-looking widgets? | 118,138 | <p>I have read that it is possible to <a href="http://developer.imendio.com/projects/gtk-macosx/build-instructions" rel="nofollow">build GTK+ on MacOS X</a>. I know that it's possible to create a <a href="http://developer.imendio.com/projects/gtk-macosx/creating-app-bundles" rel="nofollow">bundle of a GTK+ application on MacOS</a>. I also know that it's possible to create widgets <a href="http://people.imendio.com/richard/archives/2008/02/native_mac_them_1.html" rel="nofollow">that look sort of native</a>. However, searching around I am not really clear on how to create a bundle that includes the native theme stuff, and uses Python rather than its own C main-point. There are also rumors <a href="http://developer.imendio.com/node/175" rel="nofollow">that it's possible to build PyGTK</a>, but it sounds like there might still be some wrinkles in that process.</p>
<p>However, there is no step-by-step guide that explains how one can set up an environment where an application might be run from Python source, then built and deployed in an app bundle. How can I go about doing that?</p>
| 7 | 2008-09-22T23:04:07Z | 121,180 | <p>I'm not sure if I'm grokking all the details of your question, but looking at your problem in general (how do I deploy a python app on mac), I'm inclined to say that the answer is <a href="http://undefined.org/python/py2app.html" rel="nofollow">py2app</a>. Basically this will bundle a python interpreter and all relevant python files for you, and give you a scriptable system that you can use to add in whatever other resources/dependencies you need. </p>
| 1 | 2008-09-23T14:03:07Z | [
"python",
"osx",
"gtk",
"pygtk"
] |
How do I develop and create a self-contained PyGTK application bundle for MacOS, with native-looking widgets? | 118,138 | <p>I have read that it is possible to <a href="http://developer.imendio.com/projects/gtk-macosx/build-instructions" rel="nofollow">build GTK+ on MacOS X</a>. I know that it's possible to create a <a href="http://developer.imendio.com/projects/gtk-macosx/creating-app-bundles" rel="nofollow">bundle of a GTK+ application on MacOS</a>. I also know that it's possible to create widgets <a href="http://people.imendio.com/richard/archives/2008/02/native_mac_them_1.html" rel="nofollow">that look sort of native</a>. However, searching around I am not really clear on how to create a bundle that includes the native theme stuff, and uses Python rather than its own C main-point. There are also rumors <a href="http://developer.imendio.com/node/175" rel="nofollow">that it's possible to build PyGTK</a>, but it sounds like there might still be some wrinkles in that process.</p>
<p>However, there is no step-by-step guide that explains how one can set up an environment where an application might be run from Python source, then built and deployed in an app bundle. How can I go about doing that?</p>
| 7 | 2008-09-22T23:04:07Z | 126,313 | <p>While it's not a guide <em>solely</em> targetted at python/GTK+/OS X, <a href="http://groups.google.com/group/reinteract/msg/4846099674d2153a" rel="nofollow">this post</a> is a good, detailed description of someone else's attempt to do most of what you describe. Obviously, the app-specific stuff is going to vary.</p>
| 1 | 2008-09-24T10:03:37Z | [
"python",
"osx",
"gtk",
"pygtk"
] |
How do I develop and create a self-contained PyGTK application bundle for MacOS, with native-looking widgets? | 118,138 | <p>I have read that it is possible to <a href="http://developer.imendio.com/projects/gtk-macosx/build-instructions" rel="nofollow">build GTK+ on MacOS X</a>. I know that it's possible to create a <a href="http://developer.imendio.com/projects/gtk-macosx/creating-app-bundles" rel="nofollow">bundle of a GTK+ application on MacOS</a>. I also know that it's possible to create widgets <a href="http://people.imendio.com/richard/archives/2008/02/native_mac_them_1.html" rel="nofollow">that look sort of native</a>. However, searching around I am not really clear on how to create a bundle that includes the native theme stuff, and uses Python rather than its own C main-point. There are also rumors <a href="http://developer.imendio.com/node/175" rel="nofollow">that it's possible to build PyGTK</a>, but it sounds like there might still be some wrinkles in that process.</p>
<p>However, there is no step-by-step guide that explains how one can set up an environment where an application might be run from Python source, then built and deployed in an app bundle. How can I go about doing that?</p>
| 7 | 2008-09-22T23:04:07Z | 126,346 | <p>Native looking widgets is quite complicated.
There's a beginning of quartz engine (for theming) found here <a href="http://git.gnome.org/browse/gtk+/tree/gdk/quartz" rel="nofollow">http://git.gnome.org/browse/gtk+/tree/gdk/quartz</a>
For self-contained applications check out the newly released bundle on <a href="http://live.gnome.org/GTK%2B/OSX" rel="nofollow">http://live.gnome.org/GTK%2B/OSX</a></p>
| 3 | 2008-09-24T10:12:16Z | [
"python",
"osx",
"gtk",
"pygtk"
] |
Python Regex vs PHP Regex | 118,143 | <p>No not a competition, it is instead me trying to find why a certain regex works in one but not the other.</p>
<pre><code>(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
</code></pre>
<p>That's my Regex and I'm trying to run it on</p>
<pre><code>127.255.0.0
</code></pre>
<p>Using Pythons regex I get nothing, using PHP I match it, below are the two calls I am making (just incase it's something to do with that). Essentially I am trying to work out why it works in PHP but not Python.</p>
<pre><code>re.findall(regex, string)
preg_match_all($regex, $string, $matches);
</code></pre>
<p><hr>
Solution found, it was due to the way that I was iterating through the results, this regex turned them into groups and then it didn't want to print them out in the same way etc etc. Thank you all for your help, it's really appreciated :)</p>
| 3 | 2008-09-22T23:06:02Z | 118,163 | <p>It works for me. You must be doing something wrong.</p>
<pre><code>>>> re.match(r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', '127.255.0.0').groups()
('127', '255', '0', '0')
</code></pre>
<p>Don't forget to escape the regex using raw strings: <code>r'regex_here'</code> as stated in the <a href="http://docs.python.org/dev/howto/regex.html" rel="nofollow">Regex Howto</a></p>
| 7 | 2008-09-22T23:10:13Z | [
"php",
"python",
"regex"
] |
Python Regex vs PHP Regex | 118,143 | <p>No not a competition, it is instead me trying to find why a certain regex works in one but not the other.</p>
<pre><code>(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
</code></pre>
<p>That's my Regex and I'm trying to run it on</p>
<pre><code>127.255.0.0
</code></pre>
<p>Using Pythons regex I get nothing, using PHP I match it, below are the two calls I am making (just incase it's something to do with that). Essentially I am trying to work out why it works in PHP but not Python.</p>
<pre><code>re.findall(regex, string)
preg_match_all($regex, $string, $matches);
</code></pre>
<p><hr>
Solution found, it was due to the way that I was iterating through the results, this regex turned them into groups and then it didn't want to print them out in the same way etc etc. Thank you all for your help, it's really appreciated :)</p>
| 3 | 2008-09-22T23:06:02Z | 118,165 | <p>That regular expression matches here, no idea what you are doing wrong:</p>
<pre><code>>>> import re
>>> x = re.compile(r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|'
... r'2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9]'
... r'[0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)')
>>> x.match("127.0.0.1")
<_sre.SRE_Match object at 0x5a8860>
>>> x.match("127.255.0.1")
<_sre.SRE_Match object at 0x5a8910>
>>> x.match("127.255.0.0")
<_sre.SRE_Match object at 0x5a8860>
</code></pre>
<p>Please note that <code>preg_match</code> translates to <code>re.search</code> in Python and not <code>re.match</code>. <code>re.match</code> is for useful for lexing because it's anchored.</p>
| 1 | 2008-09-22T23:10:35Z | [
"php",
"python",
"regex"
] |
Python Regex vs PHP Regex | 118,143 | <p>No not a competition, it is instead me trying to find why a certain regex works in one but not the other.</p>
<pre><code>(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
</code></pre>
<p>That's my Regex and I'm trying to run it on</p>
<pre><code>127.255.0.0
</code></pre>
<p>Using Pythons regex I get nothing, using PHP I match it, below are the two calls I am making (just incase it's something to do with that). Essentially I am trying to work out why it works in PHP but not Python.</p>
<pre><code>re.findall(regex, string)
preg_match_all($regex, $string, $matches);
</code></pre>
<p><hr>
Solution found, it was due to the way that I was iterating through the results, this regex turned them into groups and then it didn't want to print them out in the same way etc etc. Thank you all for your help, it's really appreciated :)</p>
| 3 | 2008-09-22T23:06:02Z | 118,180 | <p><a href="http://www.regular-expressions.info/php.html" rel="nofollow">PHP</a> uses 3 different flavors of regex, while python uses only one. I don't code in python, so I make no expert claims on how it uses REGEX. <a href="http://oreilly.com/catalog/9781565922570/" rel="nofollow">O'Reilly Mastering Regular Expressions</a> is a great book, as most of their works are.</p>
| 1 | 2008-09-22T23:14:25Z | [
"php",
"python",
"regex"
] |
Python Regex vs PHP Regex | 118,143 | <p>No not a competition, it is instead me trying to find why a certain regex works in one but not the other.</p>
<pre><code>(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
</code></pre>
<p>That's my Regex and I'm trying to run it on</p>
<pre><code>127.255.0.0
</code></pre>
<p>Using Pythons regex I get nothing, using PHP I match it, below are the two calls I am making (just incase it's something to do with that). Essentially I am trying to work out why it works in PHP but not Python.</p>
<pre><code>re.findall(regex, string)
preg_match_all($regex, $string, $matches);
</code></pre>
<p><hr>
Solution found, it was due to the way that I was iterating through the results, this regex turned them into groups and then it didn't want to print them out in the same way etc etc. Thank you all for your help, it's really appreciated :)</p>
| 3 | 2008-09-22T23:06:02Z | 118,181 | <p>I would suggest that using a regex for decimal range validation is not necessarily the correct answer for this problem. This is far more readable:</p>
<pre><code>def valid_ip(s):
m = re.match(r"(\d+)\.(\d+)\.(\d+)\.(\d+)$", s)
if m is None:
return False
parts = [int(m.group(1+x)) for x in range(4)]
if max(parts) > 255:
return False
return True
</code></pre>
| 4 | 2008-09-22T23:14:34Z | [
"php",
"python",
"regex"
] |
Python Regex vs PHP Regex | 118,143 | <p>No not a competition, it is instead me trying to find why a certain regex works in one but not the other.</p>
<pre><code>(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
</code></pre>
<p>That's my Regex and I'm trying to run it on</p>
<pre><code>127.255.0.0
</code></pre>
<p>Using Pythons regex I get nothing, using PHP I match it, below are the two calls I am making (just incase it's something to do with that). Essentially I am trying to work out why it works in PHP but not Python.</p>
<pre><code>re.findall(regex, string)
preg_match_all($regex, $string, $matches);
</code></pre>
<p><hr>
Solution found, it was due to the way that I was iterating through the results, this regex turned them into groups and then it didn't want to print them out in the same way etc etc. Thank you all for your help, it's really appreciated :)</p>
| 3 | 2008-09-22T23:06:02Z | 118,182 | <p>Without further details, I'd guess it's quote escaping of some kind. Both PHP and python's RegEX objects take strings as arguments. These strings will be escaped by the languge before being passed on to the RegEx engine.</p>
<p>I always using Python's "raw" string format when working with regular expressions. It ensure that "<a href="http://www.amk.ca/python/howto/regex/" rel="nofollow">backslashes are not handled in any special way</a>"</p>
<pre><code>r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
</code></pre>
| 2 | 2008-09-22T23:14:43Z | [
"php",
"python",
"regex"
] |
Python Regex vs PHP Regex | 118,143 | <p>No not a competition, it is instead me trying to find why a certain regex works in one but not the other.</p>
<pre><code>(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
</code></pre>
<p>That's my Regex and I'm trying to run it on</p>
<pre><code>127.255.0.0
</code></pre>
<p>Using Pythons regex I get nothing, using PHP I match it, below are the two calls I am making (just incase it's something to do with that). Essentially I am trying to work out why it works in PHP but not Python.</p>
<pre><code>re.findall(regex, string)
preg_match_all($regex, $string, $matches);
</code></pre>
<p><hr>
Solution found, it was due to the way that I was iterating through the results, this regex turned them into groups and then it didn't want to print them out in the same way etc etc. Thank you all for your help, it's really appreciated :)</p>
| 3 | 2008-09-22T23:06:02Z | 198,882 | <p>Just because you <em>can</em> do it with regex, doesn't mean you should. It would be much better to write instructions like: split the string on the period, make sure each group is numeric and within a certain range of numbers.</p>
<p>If you want to use a regex, just verify that it kind of "looks like" an IP address, as with Greg's regex.</p>
| 3 | 2008-10-13T20:16:59Z | [
"php",
"python",
"regex"
] |
What's the best dispatcher/callback library in Python? | 118,221 | <p>I need to allow other Python applications to register callback functions for events in my application. These need to have priorities associated with them (so a callback with a priority of 10 runs before a callback with a priority of 1) and callback functions need to be able to signal errors to the dispatcher.</p>
<p>These are all lightweight callbacks running in the same process, so I don't need to send signals across process boundaries.</p>
<p>Is there a good Python library to handle this, or do I need to write my own?</p>
| 2 | 2008-09-22T23:28:37Z | 118,227 | <p>Are these other applications running in another address space? If so, you'll need to use an interprocess communication library like <a href="http://www.freedesktop.org/wiki/Software/dbus" rel="nofollow">D-BUS</a>.</p>
<p>If you're just sending signals in the same process, try <a href="http://pypi.python.org/pypi/PyDispatcher/2.0.1" rel="nofollow">PyDispatcher</a></p>
| 1 | 2008-09-22T23:30:39Z | [
"python"
] |
What's the best dispatcher/callback library in Python? | 118,221 | <p>I need to allow other Python applications to register callback functions for events in my application. These need to have priorities associated with them (so a callback with a priority of 10 runs before a callback with a priority of 1) and callback functions need to be able to signal errors to the dispatcher.</p>
<p>These are all lightweight callbacks running in the same process, so I don't need to send signals across process boundaries.</p>
<p>Is there a good Python library to handle this, or do I need to write my own?</p>
| 2 | 2008-09-22T23:28:37Z | 118,228 | <p>What platform are you running under? GObject is the basis of the GTK GUI that's widely-used under Linux, and it supports event loops with prioritizable events like this.</p>
| 0 | 2008-09-22T23:30:44Z | [
"python"
] |
What's the best dispatcher/callback library in Python? | 118,221 | <p>I need to allow other Python applications to register callback functions for events in my application. These need to have priorities associated with them (so a callback with a priority of 10 runs before a callback with a priority of 1) and callback functions need to be able to signal errors to the dispatcher.</p>
<p>These are all lightweight callbacks running in the same process, so I don't need to send signals across process boundaries.</p>
<p>Is there a good Python library to handle this, or do I need to write my own?</p>
| 2 | 2008-09-22T23:28:37Z | 1,140,282 | <p>Try Twisted for anything network-related. Its perspective broker is quite nice to use. </p>
| 0 | 2009-07-16T21:01:38Z | [
"python"
] |
What's the best dispatcher/callback library in Python? | 118,221 | <p>I need to allow other Python applications to register callback functions for events in my application. These need to have priorities associated with them (so a callback with a priority of 10 runs before a callback with a priority of 1) and callback functions need to be able to signal errors to the dispatcher.</p>
<p>These are all lightweight callbacks running in the same process, so I don't need to send signals across process boundaries.</p>
<p>Is there a good Python library to handle this, or do I need to write my own?</p>
| 2 | 2008-09-22T23:28:37Z | 3,491,737 | <p>Try python-callbacks - <a href="http://code.google.com/p/python-callbacks/" rel="nofollow">http://code.google.com/p/python-callbacks/</a>.</p>
| 0 | 2010-08-16T08:52:15Z | [
"python"
] |
How to start IDLE (Python editor) without using the shortcut on Windows Vista? | 118,260 | <p>I'm trying to teach Komodo to fire up <a href="http://en.wikipedia.org/wiki/IDLE%5F%28Python%29">IDLE</a> when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up.</p>
<p>I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out.</p>
<p>How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.</p>
| 43 | 2008-09-22T23:44:21Z | 118,275 | <p>There's a file called idle.py in your Python installation directory in Lib\idlelib\idle.py</p>
<p>If you run that file with Python, then IDLE should start.</p>
<blockquote>
<p>c:\Python25\pythonw.exe c:\Python25\Lib\idlelib\idle.py</p>
</blockquote>
| 53 | 2008-09-22T23:49:11Z | [
"python",
"python-idle",
"komodo",
"pywin"
] |
How to start IDLE (Python editor) without using the shortcut on Windows Vista? | 118,260 | <p>I'm trying to teach Komodo to fire up <a href="http://en.wikipedia.org/wiki/IDLE%5F%28Python%29">IDLE</a> when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up.</p>
<p>I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out.</p>
<p>How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.</p>
| 43 | 2008-09-22T23:44:21Z | 118,308 | <p>Here's another path you can use. I'm not sure if this is part of the standard distribution or if the file is automatically created on first use of the IDLE.</p>
<pre><code>C:\Python25\Lib\idlelib\idle.pyw
</code></pre>
| 8 | 2008-09-22T23:56:03Z | [
"python",
"python-idle",
"komodo",
"pywin"
] |
How to start IDLE (Python editor) without using the shortcut on Windows Vista? | 118,260 | <p>I'm trying to teach Komodo to fire up <a href="http://en.wikipedia.org/wiki/IDLE%5F%28Python%29">IDLE</a> when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up.</p>
<p>I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out.</p>
<p>How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.</p>
| 43 | 2008-09-22T23:44:21Z | 1,537,046 | <p>You can also assign hotkeys to Windows shortcuts directly (at least in Windows 95 you could, I haven't checked again since then, but I think the option should be still there ^_^).</p>
| 1 | 2009-10-08T10:51:18Z | [
"python",
"python-idle",
"komodo",
"pywin"
] |
How to start IDLE (Python editor) without using the shortcut on Windows Vista? | 118,260 | <p>I'm trying to teach Komodo to fire up <a href="http://en.wikipedia.org/wiki/IDLE%5F%28Python%29">IDLE</a> when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up.</p>
<p>I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out.</p>
<p>How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.</p>
| 43 | 2008-09-22T23:44:21Z | 7,394,470 | <p>In Python 3.2.2, I found <code>\Python32\Lib\idlelib\idle.bat</code> which was useful because it would let me open python files supplied as args in IDLE.</p>
| 10 | 2011-09-12T21:48:51Z | [
"python",
"python-idle",
"komodo",
"pywin"
] |
How to start IDLE (Python editor) without using the shortcut on Windows Vista? | 118,260 | <p>I'm trying to teach Komodo to fire up <a href="http://en.wikipedia.org/wiki/IDLE%5F%28Python%29">IDLE</a> when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up.</p>
<p>I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out.</p>
<p>How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.</p>
| 43 | 2008-09-22T23:44:21Z | 8,237,399 | <p>If you just have a Python shell running, type:</p>
<pre><code>import idlelib.PyShell
idlelib.PyShell.main()
</code></pre>
| 8 | 2011-11-23T04:35:54Z | [
"python",
"python-idle",
"komodo",
"pywin"
] |
How to start IDLE (Python editor) without using the shortcut on Windows Vista? | 118,260 | <p>I'm trying to teach Komodo to fire up <a href="http://en.wikipedia.org/wiki/IDLE%5F%28Python%29">IDLE</a> when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up.</p>
<p>I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out.</p>
<p>How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.</p>
| 43 | 2008-09-22T23:44:21Z | 18,023,426 | <p>Python installation folder > Lib > idlelib > idle.pyw</p>
<p>Double click on it and you're good to go.</p>
| 3 | 2013-08-02T18:05:55Z | [
"python",
"python-idle",
"komodo",
"pywin"
] |
How to start IDLE (Python editor) without using the shortcut on Windows Vista? | 118,260 | <p>I'm trying to teach Komodo to fire up <a href="http://en.wikipedia.org/wiki/IDLE%5F%28Python%29">IDLE</a> when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up.</p>
<p>I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out.</p>
<p>How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.</p>
| 43 | 2008-09-22T23:44:21Z | 33,572,951 | <p>The idle shortcut is an "Advertised Shortcut" which breaks certain features like the "find target" button. Google for more info.</p>
<p>You can view the link with a hex editor or download <a href="https://code.google.com/p/lnk-parser/" rel="nofollow">LNK Parser</a> to see where it points to.</p>
<p>In my case it runs:<br>
<code>..\..\..\..\..\Python27\pythonw.exe "C:\Python27\Lib\idlelib\idle.pyw"</code></p>
| 1 | 2015-11-06T18:06:16Z | [
"python",
"python-idle",
"komodo",
"pywin"
] |
How to start IDLE (Python editor) without using the shortcut on Windows Vista? | 118,260 | <p>I'm trying to teach Komodo to fire up <a href="http://en.wikipedia.org/wiki/IDLE%5F%28Python%29">IDLE</a> when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up.</p>
<p>I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out.</p>
<p>How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.</p>
| 43 | 2008-09-22T23:44:21Z | 35,535,565 | <p>there is a .bat script to start it (python 2.7).</p>
<pre><code>c:\Python27\Lib\idlelib\idle.bat
</code></pre>
| 1 | 2016-02-21T11:33:34Z | [
"python",
"python-idle",
"komodo",
"pywin"
] |
How do you use the ellipsis slicing syntax in Python? | 118,370 | <p>This came up in <a href="http://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a>, but I can't see good documentation or examples that explain how the feature works.</p>
| 114 | 2008-09-23T00:17:09Z | 118,395 | <p>You'd use it in your own class, since no builtin class makes use of it.</p>
<p>Numpy uses it, as stated in the <a href="http://wiki.scipy.org/Numpy_Example_List_With_Doc#head-490d781b49b68b300eedaef32369fae7d58627fb">documentation</a>. Some examples <a href="http://wiki.scipy.org/Tentative_NumPy_Tutorial#head-864862d3f2bb4c32f04260fac61eb4ef34788c4c">here</a>.</p>
<p>In your own class, you'd use it like this:</p>
<pre><code>>>> class TestEllipsis(object):
... def __getitem__(self, item):
... if item is Ellipsis:
... return "Returning all items"
... else:
... return "return %r items" % item
...
>>> x = TestEllipsis()
>>> print x[2]
return 2 items
>>> print x[...]
Returning all items
</code></pre>
<p>Of course, there is the <a href="https://docs.python.org/library/constants.html#Ellipsis">python documentation</a>, and <a href="https://docs.python.org/reference/expressions.html#grammar-token-slicing">language reference</a>. But those aren't very helpful. </p>
| 70 | 2008-09-23T00:24:21Z | [
"python",
"numpy",
"subclass",
"slice",
"ellipsis"
] |
How do you use the ellipsis slicing syntax in Python? | 118,370 | <p>This came up in <a href="http://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a>, but I can't see good documentation or examples that explain how the feature works.</p>
| 114 | 2008-09-23T00:17:09Z | 118,508 | <p>The ellipsis is used to slice higher-dimensional data structures. </p>
<p>It's designed to mean <em>at this point, insert as many full slices (<code>:</code>) to extend the multi-dimensional slice to all dimensions</em>.</p>
<p><strong>Example</strong>:</p>
<pre><code>>>> from numpy import arange
>>> a = arange(16).reshape(2,2,2,2)
</code></pre>
<p>Now, you have a 4-dimensional matrix of order 2x2x2x2. To select all first elements in the 4th dimension, you can use the ellipsis notation</p>
<pre><code>>>> a[..., 0].flatten()
array([ 0, 2, 4, 6, 8, 10, 12, 14])
</code></pre>
<p>which is equivalent to</p>
<pre><code>>>> a[:,:,:,0].flatten()
array([ 0, 2, 4, 6, 8, 10, 12, 14])
</code></pre>
<p>In your own implementations, you're free to ignore the contract mentioned above and use it for whatever you see fit.</p>
| 159 | 2008-09-23T00:55:09Z | [
"python",
"numpy",
"subclass",
"slice",
"ellipsis"
] |
How do you use the ellipsis slicing syntax in Python? | 118,370 | <p>This came up in <a href="http://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a>, but I can't see good documentation or examples that explain how the feature works.</p>
| 114 | 2008-09-23T00:17:09Z | 120,055 | <p>This is another use for Ellipsis, which has nothing to do with slices: I often use it in intra-thread communication with queues, as a mark that signals "Done"; it's there, it's an object, it's a singleton, and its name means "lack of", and it's not the overused None (which could be put in a queue as part of normal data flow). YMMV.</p>
<p>P.S: I don't mind downvotes, when what I say in an answer is not useful in relation to the question; then I try to improve my answer. But I sure can't understand how one can downvote <em>any</em> of the answers in this questionâ when the question is âhow do <em>you</em> use the Ellipsis in Pythonâ⦠It seems that people think that downvoting means âI disagreeâ or âI don't like thisâ.</p>
| 66 | 2008-09-23T09:34:48Z | [
"python",
"numpy",
"subclass",
"slice",
"ellipsis"
] |
How do you use the ellipsis slicing syntax in Python? | 118,370 | <p>This came up in <a href="http://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a>, but I can't see good documentation or examples that explain how the feature works.</p>
| 114 | 2008-09-23T00:17:09Z | 17,763,926 | <p>Python documentation aren't very clear about this but there is another use of ellipsis. It is used as a representation of infinite data structures in case of Python. <a href="http://stackoverflow.com/questions/17160162/what-is-in-python-2-7">This question</a> discusses how and some actual applications.</p>
| 0 | 2013-07-20T15:47:51Z | [
"python",
"numpy",
"subclass",
"slice",
"ellipsis"
] |
How can I join a list into a string (caveat)? | 118,458 | <p>Along the lines of my previous <a href="http://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat">question</a>, how can i join a list of strings into a string such that values get quoted cleanly. Something like:</p>
<pre><code>['a', 'one "two" three', 'foo, bar', """both"'"""]
</code></pre>
<p>into:</p>
<pre><code>a, 'one "two" three', "foo, bar", "both\"'"
</code></pre>
<p>I suspect that the csv module will come into play here, but i'm not sure how to get the output I want.</p>
| 6 | 2008-09-23T00:41:25Z | 118,462 | <p>Using the <code>csv</code> module you can do that way:</p>
<pre><code>import csv
writer = csv.writer(open("some.csv", "wb"))
writer.writerow(the_list)
</code></pre>
<p>If you need a string just use <code>StringIO</code> instance as a file:</p>
<pre><code>f = StringIO.StringIO()
writer = csv.writer(f)
writer.writerow(the_list)
print f.getvalue()
</code></pre>
<p>The output: <code>a,"one ""two"" three","foo, bar","both""'"</code></p>
<p><code>csv</code> will write in a way it can read back later.
You can fine-tune its output by defining a <code>dialect</code>, just set <code>quotechar</code>, <code>escapechar</code>, etc, as needed:</p>
<pre><code>class SomeDialect(csv.excel):
delimiter = ','
quotechar = '"'
escapechar = "\\"
doublequote = False
lineterminator = '\n'
quoting = csv.QUOTE_MINIMAL
f = cStringIO.StringIO()
writer = csv.writer(f, dialect=SomeDialect)
writer.writerow(the_list)
print f.getvalue()
</code></pre>
<p>The output: <code>a,one \"two\" three,"foo, bar",both\"'</code></p>
<p>The same dialect can be used with csv module to read the string back later to a list.</p>
| 7 | 2008-09-23T00:43:42Z | [
"python",
"string",
"list",
"csv"
] |
How can I join a list into a string (caveat)? | 118,458 | <p>Along the lines of my previous <a href="http://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat">question</a>, how can i join a list of strings into a string such that values get quoted cleanly. Something like:</p>
<pre><code>['a', 'one "two" three', 'foo, bar', """both"'"""]
</code></pre>
<p>into:</p>
<pre><code>a, 'one "two" three', "foo, bar", "both\"'"
</code></pre>
<p>I suspect that the csv module will come into play here, but i'm not sure how to get the output I want.</p>
| 6 | 2008-09-23T00:41:25Z | 118,625 | <p>Here's a slightly simpler alternative.</p>
<pre><code>def quote(s):
if "'" in s or '"' in s or "," in str(s):
return repr(s)
return s
</code></pre>
<p>We only need to quote a value that might have commas or quotes.</p>
<pre><code>>>> x= ['a', 'one "two" three', 'foo, bar', 'both"\'']
>>> print ", ".join( map(quote,x) )
a, 'one "two" three', 'foo, bar', 'both"\''
</code></pre>
| 1 | 2008-09-23T01:26:34Z | [
"python",
"string",
"list",
"csv"
] |
How can I join a list into a string (caveat)? | 118,458 | <p>Along the lines of my previous <a href="http://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat">question</a>, how can i join a list of strings into a string such that values get quoted cleanly. Something like:</p>
<pre><code>['a', 'one "two" three', 'foo, bar', """both"'"""]
</code></pre>
<p>into:</p>
<pre><code>a, 'one "two" three', "foo, bar", "both\"'"
</code></pre>
<p>I suspect that the csv module will come into play here, but i'm not sure how to get the output I want.</p>
| 6 | 2008-09-23T00:41:25Z | 121,745 | <p>On a related note, Python's <a href="http://docs.python.org/lib/standard-encodings.html" rel="nofollow">builtin encoders</a> can also do string escaping:</p>
<pre><code>>>> print "that's interesting".encode('string_escape')
that\'s interesting
</code></pre>
| 2 | 2008-09-23T15:29:04Z | [
"python",
"string",
"list",
"csv"
] |
How do I create a non-standard type with SOAPpy? | 118,467 | <p>I am calling <a href="http://www.pingdom.com/services/api-documentation/" rel="nofollow">a WSDL web service</a> from Python using <a href="http://pywebsvcs.sourceforge.net/" rel="nofollow">SOAPpy</a>. The call I need to make is to the method <a href="http://www.pingdom.com/services/api-documentation/operation_login" rel="nofollow">Auth_login</a>. This has 2 arguments - the first, a string being the API key; the second, a <a href="http://www.pingdom.com/services/api-documentation/class_CredentialsData" rel="nofollow">custom type containing username and password</a>. The custom type is called Auth_credentialsData which contains 2 values as stings - one for the username and one for the password. How can I create this custom type using SOAPpy? I tried passing a list and a dictionary, none of which work.</p>
<p>Code so far:</p>
<pre><code>from SOAPpy import WSDL
wsdlUrl = 'https://ws.pingdom.com/soap/PingdomAPI.wsdl'
client = WSDL.Proxy(wsdlUrl)
</code></pre>
<p>Tried both:</p>
<pre><code>credentials = ['[email protected]', 'password']
client.Auth_login('key', credentials)
</code></pre>
<p>and</p>
<pre><code>credentials = {'username': '[email protected]', 'password': 'passsword'}
client.Auth_login('key', credentials)
</code></pre>
<p>both of which give an authentication failed error.</p>
| 2 | 2008-09-23T00:46:14Z | 118,507 | <p>The better method is to use the ZSI soap module which allows you to take a WDSL file and turn it into classes and methods that you can then use to call it. The online documentation is <a href="http://pywebsvcs.sourceforge.net/zsi.html#SECTION0012300000000000000000" rel="nofollow"> on their website</a> but the latest documentation is more easily found in the source package. If you install in Debian/Ubuntu (package name python-zsi) the documentation is in /usr/share/doc/python-zsi in a pair of PDFs you can find in there.</p>
| 0 | 2008-09-23T00:54:58Z | [
"python",
"web-services",
"soap"
] |
How do I read an Excel file into Python using xlrd? Can it read newer Office formats? | 118,516 | <p>My issue is below but would be interested comments from anyone with experience with xlrd.</p>
<p>I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: <a href="http://www.djindexes.com/mdsidx/?event=showAverages">http://www.djindexes.com/mdsidx/?event=showAverages</a>)</p>
<p>When I open the file unmodified I get a nasty BIFF error (binary format not recognized)</p>
<p>However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: <a href="http://skitch.com/alok/ssa3/componentreport-dji.xls-properties">http://skitch.com/alok/ssa3/componentreport-dji.xls-properties</a>)</p>
<p>If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls</p>
<p>Here is a pastebin of an ipython session replicating the issue: <a href="http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq">http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq</a></p>
<p>Any thoughts on:
How to trick xlrd into recognizing the file so I can extract data?
How to use python to automate the explicit 'save as' format to one that xlrd will accept?
Plan B?</p>
| 10 | 2008-09-23T00:58:09Z | 118,586 | <p>Well here is some code that I did: (look down the bottom): <a href="http://anonsvn.labs.jboss.com/labs/jbossrules/trunk/drools-decisiontables/src/main/resources/python-dt/pydt.py" rel="nofollow">here</a></p>
<p>Not sure about the newer formats - if xlrd can't read it, xlrd needs to have a new version released !</p>
| 0 | 2008-09-23T01:14:51Z | [
"python",
"xlrd",
"import-from-excel"
] |
How do I read an Excel file into Python using xlrd? Can it read newer Office formats? | 118,516 | <p>My issue is below but would be interested comments from anyone with experience with xlrd.</p>
<p>I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: <a href="http://www.djindexes.com/mdsidx/?event=showAverages">http://www.djindexes.com/mdsidx/?event=showAverages</a>)</p>
<p>When I open the file unmodified I get a nasty BIFF error (binary format not recognized)</p>
<p>However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: <a href="http://skitch.com/alok/ssa3/componentreport-dji.xls-properties">http://skitch.com/alok/ssa3/componentreport-dji.xls-properties</a>)</p>
<p>If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls</p>
<p>Here is a pastebin of an ipython session replicating the issue: <a href="http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq">http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq</a></p>
<p>Any thoughts on:
How to trick xlrd into recognizing the file so I can extract data?
How to use python to automate the explicit 'save as' format to one that xlrd will accept?
Plan B?</p>
| 10 | 2008-09-23T00:58:09Z | 118,803 | <p>Do you have to use xlrd? I just downloaded 'UPDATED - Dow Jones Industrial Average Movers - 2008' from that website and had no trouble reading it with <a href="http://sourceforge.net/projects/pyexcelerator" rel="nofollow">pyExcelerator</a>.</p>
<pre><code>import pyExcelerator
book = pyExcelerator.parse_xls('DJIAMovers.xls')
</code></pre>
| -1 | 2008-09-23T02:33:40Z | [
"python",
"xlrd",
"import-from-excel"
] |
How do I read an Excel file into Python using xlrd? Can it read newer Office formats? | 118,516 | <p>My issue is below but would be interested comments from anyone with experience with xlrd.</p>
<p>I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: <a href="http://www.djindexes.com/mdsidx/?event=showAverages">http://www.djindexes.com/mdsidx/?event=showAverages</a>)</p>
<p>When I open the file unmodified I get a nasty BIFF error (binary format not recognized)</p>
<p>However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: <a href="http://skitch.com/alok/ssa3/componentreport-dji.xls-properties">http://skitch.com/alok/ssa3/componentreport-dji.xls-properties</a>)</p>
<p>If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls</p>
<p>Here is a pastebin of an ipython session replicating the issue: <a href="http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq">http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq</a></p>
<p>Any thoughts on:
How to trick xlrd into recognizing the file so I can extract data?
How to use python to automate the explicit 'save as' format to one that xlrd will accept?
Plan B?</p>
| 10 | 2008-09-23T00:58:09Z | 125,001 | <p>More info on pyExcelerator: To read a file, do this:</p>
<pre><code>import pyExcelerator
book = pyExcelerator.parse_xls(filename)
</code></pre>
<p>where filename is a string that is the filename to read (not a file-like object). This will give you a data structure representing the workbook: a list of pairs, where the first element of the pair is the worksheet name and the second element is the worksheet data.</p>
<p>The worksheet data is a dictionary, where the keys are (row, col) pairs (starting with 0) and the values are the cell contents -- generally int, float, or string. So, for instance, in the simple case of all the data being on the first worksheet:</p>
<pre><code>data = book[0][1]
print 'Cell A1 of worksheet %s is: %s' % (book[0][0], repr(data[(0, 0)]))
</code></pre>
<p>If the cell is empty, you'll get a KeyError. If you're dealing with dates, they <em>may</em> (I forget) come through as integers or floats; if this is the case, you'll need to convert. Basically the rule is: datetime.datetime(1899, 12, 31) + datetime.timedelta(days=n) but that might be off by 1 or 2 (because Excel treats 1900 as a leap-year for compatibility with Lotus, and because I can't remember if 1900-1-1 is 0 or 1), so do some trial-and-error to check. Datetimes are stored as floats, I think (days and fractions of a day).</p>
<p>I think there is partial support for forumulas, but I wouldn't guarantee anything.</p>
| 1 | 2008-09-24T02:05:29Z | [
"python",
"xlrd",
"import-from-excel"
] |
How do I read an Excel file into Python using xlrd? Can it read newer Office formats? | 118,516 | <p>My issue is below but would be interested comments from anyone with experience with xlrd.</p>
<p>I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: <a href="http://www.djindexes.com/mdsidx/?event=showAverages">http://www.djindexes.com/mdsidx/?event=showAverages</a>)</p>
<p>When I open the file unmodified I get a nasty BIFF error (binary format not recognized)</p>
<p>However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: <a href="http://skitch.com/alok/ssa3/componentreport-dji.xls-properties">http://skitch.com/alok/ssa3/componentreport-dji.xls-properties</a>)</p>
<p>If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls</p>
<p>Here is a pastebin of an ipython session replicating the issue: <a href="http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq">http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq</a></p>
<p>Any thoughts on:
How to trick xlrd into recognizing the file so I can extract data?
How to use python to automate the explicit 'save as' format to one that xlrd will accept?
Plan B?</p>
| 10 | 2008-09-23T00:58:09Z | 272,170 | <p>xlrd support for Office 2007/2008 (OpenXML) format is in alpha test - see the following post in the python-excel newsgroup:
<a href="http://groups.google.com/group/python-excel/msg/0c5f15ad122bf24b?hl=en" rel="nofollow">http://groups.google.com/group/python-excel/msg/0c5f15ad122bf24b?hl=en</a> </p>
| 3 | 2008-11-07T14:14:03Z | [
"python",
"xlrd",
"import-from-excel"
] |
How do I read an Excel file into Python using xlrd? Can it read newer Office formats? | 118,516 | <p>My issue is below but would be interested comments from anyone with experience with xlrd.</p>
<p>I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: <a href="http://www.djindexes.com/mdsidx/?event=showAverages">http://www.djindexes.com/mdsidx/?event=showAverages</a>)</p>
<p>When I open the file unmodified I get a nasty BIFF error (binary format not recognized)</p>
<p>However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: <a href="http://skitch.com/alok/ssa3/componentreport-dji.xls-properties">http://skitch.com/alok/ssa3/componentreport-dji.xls-properties</a>)</p>
<p>If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls</p>
<p>Here is a pastebin of an ipython session replicating the issue: <a href="http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq">http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq</a></p>
<p>Any thoughts on:
How to trick xlrd into recognizing the file so I can extract data?
How to use python to automate the explicit 'save as' format to one that xlrd will accept?
Plan B?</p>
| 10 | 2008-09-23T00:58:09Z | 694,688 | <p>FWIW, I'm the author of xlrd, and the maintainer of xlwt (a fork of pyExcelerator). A few points:</p>
<ol>
<li><p>The file ComponentReport-DJI.xls is misnamed; it is not an XLS file, it is a tab-separated-values file. Open it with a text editor (e.g. Notepad) and you'll see what I mean. You can also look at the not-very-raw raw bytes with Python:</p>
<pre><code>>>> open('ComponentReport-DJI.xls', 'rb').read(200)
'COMPANY NAME\tPRIMARY EXCHANGE\tTICKER\tSTYLE\tICB SUBSECTOR\tMARKET CAP RANGE\
tWEIGHT PCT\tUSD CLOSE\t\r\n3M Co.\tNew York SE\tMMM\tN/A\tDiversified Industria
ls\tBroad\t5.15676229508\t50.33\t\r\nAlcoa Inc.\tNew York SE\tA'
</code></pre>
<p>You can read this file using Python's csv module ... just use <code>delimiter="\t"</code> in your call to <code>csv.reader()</code>.</p></li>
<li><p>xlrd can read any file that pyExcelerator can, and read them better—dates don't come out as floats, and the full story on Excel dates is in the xlrd documentation.</p></li>
<li><p>pyExcelerator is abandonware—xlrd and xlwt are alive and well. Check out <a href="http://groups.google.com/group/python-excel">http://groups.google.com/group/python-excel</a></p></li>
</ol>
<p>HTH
John</p>
| 25 | 2009-03-29T14:21:13Z | [
"python",
"xlrd",
"import-from-excel"
] |
What is wrong with my snap to grid code? | 118,540 | <p>First of all, I'm fairly sure snapping to grid is fairly easy, however I've run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong.</p>
<p>Here's the situation</p>
<p>I have an abstract concept of a grid, with Y steps exactly Y_STEP apart (the x steps are working fine so ignore them for now)</p>
<p>The grid is in an abstract coordinate space, and to get things to line up I've got a magic offset in there, let's call it Y_OFFSET</p>
<p>to snap to the grid I've got the following code (python)</p>
<pre><code>def snapToGrid(originalPos, offset, step):
index = int((originalPos - offset) / step) #truncates the remainder away
return index * gap + offset
</code></pre>
<p>so I pass the cursor position, Y_OFFSET and Y_STEP into that function and it returns me the nearest floored y position on the grid</p>
<p>That appears to work fine in the original scenario, however when I take into account the fact that the view is scrollable things get a little weird.</p>
<p>Scrolling is made as basic as I can get it, I've got a viewPort that keeps count of the distance scrolled along the Y Axis and just offsets everything that goes through it.</p>
<p>Here's a snippet of the cursor's mouseMotion code:</p>
<pre><code>def mouseMotion(self, event):
pixelPos = event.pos[Y]
odePos = Scroll.pixelPosToOdePos(pixelPos)
self.tool.positionChanged(odePos)
</code></pre>
<p>So there's two things to look at there, first the Scroll module's translation from pixel position to the abstract coordinate space, then the tool's positionChanged function which takes the abstract coordinate space value and snaps to the nearest Y step.</p>
<p>Here's the relevant Scroll code</p>
<pre><code>def pixelPosToOdePos(pixelPos):
offsetPixelPos = pixelPos - self.viewPortOffset
return pixelsToOde(offsetPixelPos)
def pixelsToOde(pixels):
return float(pixels) / float(pixels_in_an_ode_unit)
</code></pre>
<p>And the tools update code</p>
<pre><code>def positionChanged(self, newPos):
self.snappedPos = snapToGrid(originalPos, Y_OFFSET, Y_STEP)
</code></pre>
<p>The last relevant chunk is when the tool goes to render itself. It goes through the Scroll object, which transforms the tool's snapped coordinate space position into an onscreen pixel position, here's the code:</p>
<pre><code>#in Tool
def render(self, screen):
Scroll.render(screen, self.image, self.snappedPos)
#in Scroll
def render(self, screen, image, odePos):
pixelPos = self.odePosToPixelPos(odePos)
screen.blit(image, pixelPos) # screen is a surface from pygame for the curious
def odePosToPixelPos(self.odePos):
offsetPos = odePos + self.viewPortOffset
return odeToPixels(offsetPos)
def odeToPixels(odeUnits):
return int(odeUnits * pixels_in_an_ode_unit)
</code></pre>
<p>Whew, that was a long explanation. Hope you're still with me... </p>
<p>The problem I'm now getting is that when I scroll up the drawn image loses alignment with the cursor.<br />
It starts snapping to the Y step exactly 1 step below the cursor.
Additionally it appears to phase in and out of allignment.<br />
At some scrolls it is out by 1 and other scrolls it is spot on.<br />
It's never out by more than 1 and it's always snapping to a valid grid location.</p>
<p>Best guess I can come up with is that somewhere I'm truncating some data in the wrong spot, but no idea where or how it ends up with this behavior.</p>
<p>Anyone familiar with coordinate spaces, scrolling and snapping?</p>
| 0 | 2008-09-23T01:04:10Z | 118,645 | <p>Do you have a typo in positionChanged() ?</p>
<pre><code>def positionChanged(self, newPos):
self.snappedPos = snapToGrid(newPos, Y_OFFSET, Y_STEP)
</code></pre>
<p>I guess you are off by one pixel because of the accuracy problems during float division. Try changing your snapToGrid() to this:</p>
<pre><code>def snapToGrid(originalPos, offset, step):
EPS = 1e-6
index = int((originalPos - offset) / step + EPS) #truncates the remainder away
return index * gap + offset
</code></pre>
| 0 | 2008-09-23T01:33:59Z | [
"python",
"graphics",
"grid",
"snap-framework"
] |
What is wrong with my snap to grid code? | 118,540 | <p>First of all, I'm fairly sure snapping to grid is fairly easy, however I've run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong.</p>
<p>Here's the situation</p>
<p>I have an abstract concept of a grid, with Y steps exactly Y_STEP apart (the x steps are working fine so ignore them for now)</p>
<p>The grid is in an abstract coordinate space, and to get things to line up I've got a magic offset in there, let's call it Y_OFFSET</p>
<p>to snap to the grid I've got the following code (python)</p>
<pre><code>def snapToGrid(originalPos, offset, step):
index = int((originalPos - offset) / step) #truncates the remainder away
return index * gap + offset
</code></pre>
<p>so I pass the cursor position, Y_OFFSET and Y_STEP into that function and it returns me the nearest floored y position on the grid</p>
<p>That appears to work fine in the original scenario, however when I take into account the fact that the view is scrollable things get a little weird.</p>
<p>Scrolling is made as basic as I can get it, I've got a viewPort that keeps count of the distance scrolled along the Y Axis and just offsets everything that goes through it.</p>
<p>Here's a snippet of the cursor's mouseMotion code:</p>
<pre><code>def mouseMotion(self, event):
pixelPos = event.pos[Y]
odePos = Scroll.pixelPosToOdePos(pixelPos)
self.tool.positionChanged(odePos)
</code></pre>
<p>So there's two things to look at there, first the Scroll module's translation from pixel position to the abstract coordinate space, then the tool's positionChanged function which takes the abstract coordinate space value and snaps to the nearest Y step.</p>
<p>Here's the relevant Scroll code</p>
<pre><code>def pixelPosToOdePos(pixelPos):
offsetPixelPos = pixelPos - self.viewPortOffset
return pixelsToOde(offsetPixelPos)
def pixelsToOde(pixels):
return float(pixels) / float(pixels_in_an_ode_unit)
</code></pre>
<p>And the tools update code</p>
<pre><code>def positionChanged(self, newPos):
self.snappedPos = snapToGrid(originalPos, Y_OFFSET, Y_STEP)
</code></pre>
<p>The last relevant chunk is when the tool goes to render itself. It goes through the Scroll object, which transforms the tool's snapped coordinate space position into an onscreen pixel position, here's the code:</p>
<pre><code>#in Tool
def render(self, screen):
Scroll.render(screen, self.image, self.snappedPos)
#in Scroll
def render(self, screen, image, odePos):
pixelPos = self.odePosToPixelPos(odePos)
screen.blit(image, pixelPos) # screen is a surface from pygame for the curious
def odePosToPixelPos(self.odePos):
offsetPos = odePos + self.viewPortOffset
return odeToPixels(offsetPos)
def odeToPixels(odeUnits):
return int(odeUnits * pixels_in_an_ode_unit)
</code></pre>
<p>Whew, that was a long explanation. Hope you're still with me... </p>
<p>The problem I'm now getting is that when I scroll up the drawn image loses alignment with the cursor.<br />
It starts snapping to the Y step exactly 1 step below the cursor.
Additionally it appears to phase in and out of allignment.<br />
At some scrolls it is out by 1 and other scrolls it is spot on.<br />
It's never out by more than 1 and it's always snapping to a valid grid location.</p>
<p>Best guess I can come up with is that somewhere I'm truncating some data in the wrong spot, but no idea where or how it ends up with this behavior.</p>
<p>Anyone familiar with coordinate spaces, scrolling and snapping?</p>
| 0 | 2008-09-23T01:04:10Z | 118,847 | <p>Thanks for the answer, there may be a typo, but I can't see it...</p>
<p>Unfortunately the change to snapToGrid didn't make a difference, so I don't think that's the issue.</p>
<p>It's not off by one pixel, but rather it's off by Y_STEP. Playing around with it some more I've found that I can't get it to be exact at any point that the screen is scrolled up and also that it happens towards the top of the screen, which I suspect is ODE position zero, so I'm guessing my problem is around small or negative values.</p>
| 0 | 2008-09-23T02:54:08Z | [
"python",
"graphics",
"grid",
"snap-framework"
] |
What is wrong with my snap to grid code? | 118,540 | <p>First of all, I'm fairly sure snapping to grid is fairly easy, however I've run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong.</p>
<p>Here's the situation</p>
<p>I have an abstract concept of a grid, with Y steps exactly Y_STEP apart (the x steps are working fine so ignore them for now)</p>
<p>The grid is in an abstract coordinate space, and to get things to line up I've got a magic offset in there, let's call it Y_OFFSET</p>
<p>to snap to the grid I've got the following code (python)</p>
<pre><code>def snapToGrid(originalPos, offset, step):
index = int((originalPos - offset) / step) #truncates the remainder away
return index * gap + offset
</code></pre>
<p>so I pass the cursor position, Y_OFFSET and Y_STEP into that function and it returns me the nearest floored y position on the grid</p>
<p>That appears to work fine in the original scenario, however when I take into account the fact that the view is scrollable things get a little weird.</p>
<p>Scrolling is made as basic as I can get it, I've got a viewPort that keeps count of the distance scrolled along the Y Axis and just offsets everything that goes through it.</p>
<p>Here's a snippet of the cursor's mouseMotion code:</p>
<pre><code>def mouseMotion(self, event):
pixelPos = event.pos[Y]
odePos = Scroll.pixelPosToOdePos(pixelPos)
self.tool.positionChanged(odePos)
</code></pre>
<p>So there's two things to look at there, first the Scroll module's translation from pixel position to the abstract coordinate space, then the tool's positionChanged function which takes the abstract coordinate space value and snaps to the nearest Y step.</p>
<p>Here's the relevant Scroll code</p>
<pre><code>def pixelPosToOdePos(pixelPos):
offsetPixelPos = pixelPos - self.viewPortOffset
return pixelsToOde(offsetPixelPos)
def pixelsToOde(pixels):
return float(pixels) / float(pixels_in_an_ode_unit)
</code></pre>
<p>And the tools update code</p>
<pre><code>def positionChanged(self, newPos):
self.snappedPos = snapToGrid(originalPos, Y_OFFSET, Y_STEP)
</code></pre>
<p>The last relevant chunk is when the tool goes to render itself. It goes through the Scroll object, which transforms the tool's snapped coordinate space position into an onscreen pixel position, here's the code:</p>
<pre><code>#in Tool
def render(self, screen):
Scroll.render(screen, self.image, self.snappedPos)
#in Scroll
def render(self, screen, image, odePos):
pixelPos = self.odePosToPixelPos(odePos)
screen.blit(image, pixelPos) # screen is a surface from pygame for the curious
def odePosToPixelPos(self.odePos):
offsetPos = odePos + self.viewPortOffset
return odeToPixels(offsetPos)
def odeToPixels(odeUnits):
return int(odeUnits * pixels_in_an_ode_unit)
</code></pre>
<p>Whew, that was a long explanation. Hope you're still with me... </p>
<p>The problem I'm now getting is that when I scroll up the drawn image loses alignment with the cursor.<br />
It starts snapping to the Y step exactly 1 step below the cursor.
Additionally it appears to phase in and out of allignment.<br />
At some scrolls it is out by 1 and other scrolls it is spot on.<br />
It's never out by more than 1 and it's always snapping to a valid grid location.</p>
<p>Best guess I can come up with is that somewhere I'm truncating some data in the wrong spot, but no idea where or how it ends up with this behavior.</p>
<p>Anyone familiar with coordinate spaces, scrolling and snapping?</p>
| 0 | 2008-09-23T01:04:10Z | 119,022 | <p>Ok, I'm answering my own question here, as alexk mentioned, using int to truncate was my mistake. </p>
<p>The behaviour I'm after is best modeled by math.floor().</p>
<p>Apologies, the original question does not contain enough information to really work out what the problem is. I didn't have the extra bit of information at that point.</p>
<p>With regards to the typo note, I think I may be using the context in a confusing manner... From the perspective of the positionChanged() function, the parameter is a new position coming in.<br />
From the perspective of the snapToGrid() function the parameter is an original position which is being changed to a snapped position.
The language is like that because part of it is in my event handling code and the other part is in my general services code. I should have changed it for the example</p>
| 1 | 2008-09-23T03:56:48Z | [
"python",
"graphics",
"grid",
"snap-framework"
] |
How to express this Bash command in pure Python | 118,591 | <p>I have this line in a useful Bash script that I haven't managed to translate into Python, where 'a' is a user-input number of days' worth of files to archive:</p>
<pre><code>find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \;
</code></pre>
<p>I am familiar with the os.name and getpass.getuser for the most general cross-platform elements. I also have this function to generate a list of the full names of all the files in the equivalent of ~/podcasts/current:</p>
<pre><code>def AllFiles(filepath, depth=1, flist=[]):
fpath=os.walk(filepath)
fpath=[item for item in fpath]
while depth < len(fpath):
for item in fpath[depth][-1]:
flist.append(fpath[depth][0]+os.sep+item)
depth+=1
return flist
</code></pre>
<p>First off, there must be a better way to do that, any suggestion welcome. Either way, for example, "AllFiles('/users/me/music/itunes/itunes music/podcasts')" gives the relevant list, on Windows. Presumably I should be able to go over this list and call os.stat(list_member).st_mtime and move all the stuff older than a certain number in days to the archive; I am a little stuck on that bit.</p>
<p>Of course, anything with the concision of the bash command would also be illuminating.</p>
| 1 | 2008-09-23T01:15:54Z | 118,647 | <p>That's not a Bash command, it's a <code>find</code> command. If you really want to port it to Python it's possible, but you'll never be able to write a Python version that's as concise. <code>find</code> has been optimized over 20 years to be excellent at manipulating filesystems, while Python is a general-purpose programming language.</p>
| 2 | 2008-09-23T01:34:37Z | [
"python",
"shell",
"language-comparisons"
] |
How to express this Bash command in pure Python | 118,591 | <p>I have this line in a useful Bash script that I haven't managed to translate into Python, where 'a' is a user-input number of days' worth of files to archive:</p>
<pre><code>find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \;
</code></pre>
<p>I am familiar with the os.name and getpass.getuser for the most general cross-platform elements. I also have this function to generate a list of the full names of all the files in the equivalent of ~/podcasts/current:</p>
<pre><code>def AllFiles(filepath, depth=1, flist=[]):
fpath=os.walk(filepath)
fpath=[item for item in fpath]
while depth < len(fpath):
for item in fpath[depth][-1]:
flist.append(fpath[depth][0]+os.sep+item)
depth+=1
return flist
</code></pre>
<p>First off, there must be a better way to do that, any suggestion welcome. Either way, for example, "AllFiles('/users/me/music/itunes/itunes music/podcasts')" gives the relevant list, on Windows. Presumably I should be able to go over this list and call os.stat(list_member).st_mtime and move all the stuff older than a certain number in days to the archive; I am a little stuck on that bit.</p>
<p>Of course, anything with the concision of the bash command would also be illuminating.</p>
| 1 | 2008-09-23T01:15:54Z | 118,658 | <pre><code>import os, stat
os.stat("test")[stat.ST_MTIME]
</code></pre>
<p>Will give you the mtime. I suggest fixing those in <code>walk_results[2]</code>, and then recursing, calling the function for each dir in <code>walk_results[1]</code>.</p>
| 0 | 2008-09-23T01:38:31Z | [
"python",
"shell",
"language-comparisons"
] |
How to express this Bash command in pure Python | 118,591 | <p>I have this line in a useful Bash script that I haven't managed to translate into Python, where 'a' is a user-input number of days' worth of files to archive:</p>
<pre><code>find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \;
</code></pre>
<p>I am familiar with the os.name and getpass.getuser for the most general cross-platform elements. I also have this function to generate a list of the full names of all the files in the equivalent of ~/podcasts/current:</p>
<pre><code>def AllFiles(filepath, depth=1, flist=[]):
fpath=os.walk(filepath)
fpath=[item for item in fpath]
while depth < len(fpath):
for item in fpath[depth][-1]:
flist.append(fpath[depth][0]+os.sep+item)
depth+=1
return flist
</code></pre>
<p>First off, there must be a better way to do that, any suggestion welcome. Either way, for example, "AllFiles('/users/me/music/itunes/itunes music/podcasts')" gives the relevant list, on Windows. Presumably I should be able to go over this list and call os.stat(list_member).st_mtime and move all the stuff older than a certain number in days to the archive; I am a little stuck on that bit.</p>
<p>Of course, anything with the concision of the bash command would also be illuminating.</p>
| 1 | 2008-09-23T01:15:54Z | 118,817 | <pre><code>import os
import shutil
from os import path
from os.path import join, getmtime
from time import time
archive = "bak"
current = "cur"
def archive_old_versions(days = 3):
for root, dirs, files in os.walk(current):
for name in files:
fullname = join(root, name)
if (getmtime(fullname) < time() - days * 60 * 60 * 24):
shutil.move(fullname, join(archive, name))
</code></pre>
| 5 | 2008-09-23T02:39:18Z | [
"python",
"shell",
"language-comparisons"
] |
How to express this Bash command in pure Python | 118,591 | <p>I have this line in a useful Bash script that I haven't managed to translate into Python, where 'a' is a user-input number of days' worth of files to archive:</p>
<pre><code>find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \;
</code></pre>
<p>I am familiar with the os.name and getpass.getuser for the most general cross-platform elements. I also have this function to generate a list of the full names of all the files in the equivalent of ~/podcasts/current:</p>
<pre><code>def AllFiles(filepath, depth=1, flist=[]):
fpath=os.walk(filepath)
fpath=[item for item in fpath]
while depth < len(fpath):
for item in fpath[depth][-1]:
flist.append(fpath[depth][0]+os.sep+item)
depth+=1
return flist
</code></pre>
<p>First off, there must be a better way to do that, any suggestion welcome. Either way, for example, "AllFiles('/users/me/music/itunes/itunes music/podcasts')" gives the relevant list, on Windows. Presumably I should be able to go over this list and call os.stat(list_member).st_mtime and move all the stuff older than a certain number in days to the archive; I am a little stuck on that bit.</p>
<p>Of course, anything with the concision of the bash command would also be illuminating.</p>
| 1 | 2008-09-23T01:15:54Z | 118,879 | <pre><code>import subprocess
subprocess.call(['find', '~/podcasts/current', '-mindepth', '2', '-mtime', '+5',
'-exec', 'mv', '{}', '~/podcasts/old', ';'], shell=True)
</code></pre>
<p>That is not a joke. This python script will do exactly what the bash one does.</p>
<p><strong>EDIT</strong>: Dropped the backslash on the last param because it is not needed.</p>
| 3 | 2008-09-23T03:05:37Z | [
"python",
"shell",
"language-comparisons"
] |
Is there a way to convert indentation in Python code to braces? | 118,643 | <p>I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?</p>
| 73 | 2008-09-23T01:33:13Z | 118,651 | <p>I personally doubt that there currently is at the moment, as a lot of the Python afficionados love the fact that Python is this way, whitespace delimited.</p>
<p>I've never actually thought about that as an accessibility issue however. Maybe it's something to put forward as a bug report to Python?</p>
<p>I'd assume that you use a screen reader here however for the output? So the tabs would seem "invisible" to you? With a Braille output, it might be easier to read, but I can understand exactly how confusing this could be.</p>
<p>In fact, this is very interesting to me. I wish that I knew enough to be able to write an app that will do this for you. </p>
<p>I think it's definately something that I'll put in a bug report for, unless you've already done so yourself, or want to.</p>
<p>Edit: Also, as <a href="http://stackoverflow.com/questions/118643#118656">noted</a> by <a href="http://stackoverflow.com/users/3560/john-millikin">John Millikin</a> There is also <a href="http://timhatch.com/projects/pybraces/">PyBraces</a> Which might be a viable solution to you, and may be possible to be hacked together dependant on your coding skills to be exactly what you need (and I hope that if that's the case, you release it out for others like yourself to use)</p>
<p>Edit 2: I've just <a href="http://bugs.python.org/issue3942">reported this</a> to the python bug tracker</p>
| 10 | 2008-09-23T01:35:23Z | [
"python",
"accessibility",
"blind",
"blindness"
] |
Is there a way to convert indentation in Python code to braces? | 118,643 | <p>I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?</p>
| 73 | 2008-09-23T01:33:13Z | 118,656 | <p>You should be able to configure your editor to speak the tabs and spaces -- I know it's possible to <em>display</em> whitespace in most editors, so there must be an accessibility option somewhere to speak them.</p>
<p>Failing that, there is <a href="http://timhatch.com/projects/pybraces/" rel="nofollow">pybraces</a>, which was written as a practical joke but might actually be useful to you with a bit of work.</p>
| 6 | 2008-09-23T01:38:10Z | [
"python",
"accessibility",
"blind",
"blindness"
] |
Is there a way to convert indentation in Python code to braces? | 118,643 | <p>I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?</p>
| 73 | 2008-09-23T01:33:13Z | 118,676 | <p>I appreciate your problem, but think you are specifying the implementation instead of the problem you need solved. Instead of converting to braces, how about working on a way for your screen reader to tell you the indentation level?
<p>
For example, <a href="http://viming.blogspot.com/2007/02/indent-level-highlighting.html" rel="nofollow">some people</a> have worked on vim syntax coloring to represent python indentation levels. Perhaps a modified syntax coloring could produce something your screen reader would read?</p>
| 4 | 2008-09-23T01:43:21Z | [
"python",
"accessibility",
"blind",
"blindness"
] |
Is there a way to convert indentation in Python code to braces? | 118,643 | <p>I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?</p>
| 73 | 2008-09-23T01:33:13Z | 118,706 | <p>Although I am not blind, I have heard good things about <a href="http://emacspeak.sourceforge.net/">Emacspeak</a>. They've had a Python mode since their <a href="http://emacspeak.sourceforge.net/releases/release-8.0.html">8.0 release</a> in 1998 (they seem to be up to release 28.0!). Definitely worth checking out.</p>
| 9 | 2008-09-23T01:51:53Z | [
"python",
"accessibility",
"blind",
"blindness"
] |
Is there a way to convert indentation in Python code to braces? | 118,643 | <p>I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?</p>
| 73 | 2008-09-23T01:33:13Z | 118,738 | <p>Python supports braces for defining code blocks, and it also supports using 'begin' and 'end' tags.</p>
<p>Please see these code examples:</p>
<pre><code>class MyClass(object): #{
def myfunction(self, arg1, arg2): #{
for i in range(arg1): #{
print i
#}
#}
#}
</code></pre>
<p>And an example with bash style:</p>
<pre><code>fi = endclass = enddef = endclass = done = None
class MyClass(object):
def myfunction(self, arg1, arg2):
for i in range(arg1): #do
if i > 5: #then
print i
fi
done
enddef
endclass
</code></pre>
<p>The best thing about this is is that you can forget to put a close bracket in, and it's still valid python!</p>
<pre><code>class MyClass(object): #{
def myfunction(self, arg1, arg2): #{
for i in range(arg1): #{
print i
# whoops, forgot to close that bracket!
#}
#}
</code></pre>
<p><a href="http://www.python.org/doc/humor/#python-block-delimited-notation-parsing-explained" rel="nofollow">original gag</a></p>
<p>My real advice is to get a Braille display if you can afford one/source one - blind python programmers of my acquaintance really found a Braille display indispensable for writing python programs, it makes the indentation thing much less painful. A 40 cell display is well worth it.</p>
| 24 | 2008-09-23T02:02:25Z | [
"python",
"accessibility",
"blind",
"blindness"
] |
Is there a way to convert indentation in Python code to braces? | 118,643 | <p>I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?</p>
| 73 | 2008-09-23T01:33:13Z | 118,744 | <p>There's a solution to your problem that is distributed with python itself. <code>pindent.py</code>, it's located in the Tools\Scripts directory in a windows install (my path to it is C:\Python25\Tools\Scripts), it looks like you'd have grab it from svn.python.org if you are running on Linux or OSX. </p>
<p>It adds comments when blocks are closed, or can properly indent code if comments are put in. Here's an example of the code outputted by pindent with the command:</p>
<p><code>pindent -c myfile.py</code></p>
<pre><code>def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
# end if
else:
print 'oops!'
# end if
# end def foobar
</code></pre>
<p>Where the original <code>myfile.py</code> was: </p>
<pre><code>def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
else:
print 'oops!'
</code></pre>
<p>You can also use <code>pindent.py -d</code> to insert the correct indentation based on comments (read the header of pindent.py for details), this should allow you to code in python without worrying about indentation.</p>
<p>I'd be interested to learn what solution you end up using, if you require any further assistance, please comment on this post and I'll try to help.</p>
| 52 | 2008-09-23T02:04:01Z | [
"python",
"accessibility",
"blind",
"blindness"
] |
Is there a way to convert indentation in Python code to braces? | 118,643 | <p>I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?</p>
| 73 | 2008-09-23T01:33:13Z | 236,957 | <p>I use eclipse with the pydev extensions since it's an IDE I have a lot of experience with. I also appreciate the smart indentation it offers for coding if statements, loops, etc. I have configured the pindent.py script as an external tool that I can run on the currently focused python module which makes my life easier so I can see what is closed where with out having to constantly check indentation.</p>
| 3 | 2008-10-25T20:06:08Z | [
"python",
"accessibility",
"blind",
"blindness"
] |
Subsets and Splits