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 |
---|---|---|---|---|---|---|---|---|---|
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 4,751,601 | <p>Based on Eyecue answer (Jun 10 '10 at 21:28): this class add head() and tail() method to file object.</p>
<pre><code>class File(file):
def head(self, lines_2find=1):
self.seek(0) #Rewind file
return [self.next() for x in xrange(lines_2find)]
def tail(self, lines_2find=1):
self.seek(0, 2) #go to end of file
bytes_in_file = self.tell()
lines_found, total_bytes_scanned = 0, 0
while (lines_2find+1 > lines_found and
bytes_in_file > total_bytes_scanned):
byte_block = min(1024, bytes_in_file-total_bytes_scanned)
self.seek(-(byte_block+total_bytes_scanned), 2)
total_bytes_scanned += byte_block
lines_found += self.read(1024).count('\n')
self.seek(-total_bytes_scanned, 2)
line_list = list(self.readlines())
return line_list[-lines_2find:]
</code></pre>
<p>Usage:</p>
<pre><code>f = File('path/to/file', 'r')
f.head(3)
f.tail(3)
</code></pre>
| 1 | 2011-01-20T19:29:37Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 5,638,389 | <p>Several of these solutions have issues if the file doesn't end in \n or in ensuring the complete first line is read.</p>
<pre><code>def tail(file, n=1, bs=1024):
f = open(file)
f.seek(-1,2)
l = 1-f.read(1).count('\n') # If file doesn't end in \n, count it anyway.
B = f.tell()
while n >= l and B > 0:
block = min(bs, B)
B -= block
f.seek(B, 0)
l += f.read(block).count('\n')
f.seek(B, 0)
l = min(l,n) # discard first (incomplete) line if l > n
lines = f.readlines()[-l:]
f.close()
return lines
</code></pre>
| 1 | 2011-04-12T16:14:42Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 6,813,975 | <p>Simple and fast solution with mmap:</p>
<pre><code>import mmap
import os
def tail(filename, n):
"""Returns last n lines from the filename. No exception handling"""
size = os.path.getsize(filename)
with open(filename, "rb") as f:
# for Windows the mmap parameters are different
fm = mmap.mmap(f.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ)
try:
for i in xrange(size - 1, -1, -1):
if fm[i] == '\n':
n -= 1
if n == -1:
break
return fm[i + 1 if i else 0:].splitlines()
finally:
fm.close()
</code></pre>
| 11 | 2011-07-25T09:18:10Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 7,047,765 | <p>S.Lott's answer above almost works for me but ends up giving me partial lines. It turns out that it corrupts data on block boundaries because data holds the read blocks in reversed order. When ''.join(data) is called, the blocks are in the wrong order. This fixes that.</p>
<pre><code>def tail(f, window=20):
"""
Returns the last `window` lines of file `f` as a list.
"""
if window == 0:
return []
BUFSIZ = 1024
f.seek(0, 2)
bytes = f.tell()
size = window + 1
block = -1
data = []
while size > 0 and bytes > 0:
if bytes - BUFSIZ > 0:
# Seek back one whole BUFSIZ
f.seek(block * BUFSIZ, 2)
# read BUFFER
data.insert(0, f.read(BUFSIZ))
else:
# file too small, start from begining
f.seek(0,0)
# only read what was not read
data.insert(0, f.read(bytes))
linesFound = data[0].count('\n')
size -= linesFound
bytes -= BUFSIZ
block -= 1
return ''.join(data).splitlines()[-window:]
</code></pre>
| 18 | 2011-08-13T00:43:38Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 10,175,048 | <p>I found the Popen above to be the best solution. It's quick and dirty and it works
For python 2.6 on Unix machine i used the following</p>
<pre><code> def GetLastNLines(self, n, fileName):
"""
Name: Get LastNLines
Description: Gets last n lines using Unix tail
Output: returns last n lines of a file
Keyword argument:
n -- number of last lines to return
filename -- Name of the file you need to tail into
"""
p=subprocess.Popen(['tail','-n',str(n),self.__fileName], stdout=subprocess.PIPE)
soutput,sinput=p.communicate()
return soutput
</code></pre>
<p>soutput will have will contain last n lines of the code. to iterate through soutput line by line do:</p>
<pre><code>for line in GetLastNLines(50,'myfile.log').split('\n'):
print line
</code></pre>
| 4 | 2012-04-16T13:26:32Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 12,762,551 | <p>There are some existing implementations of tail on pypi which you can install using pip: </p>
<ul>
<li>mtFileUtil</li>
<li>multitail</li>
<li>log4tailer</li>
<li>...</li>
</ul>
<p>Depending on your situation, there may be advantages to using one of these existing tools.</p>
| 1 | 2012-10-06T18:23:37Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 13,790,289 | <p>Here is my answer. Pure python. Using timeit it seems pretty fast. Tailing 100 lines of a log file that has 100,000 lines:</p>
<pre><code>>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=10)
0.0014600753784179688
>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=100)
0.00899195671081543
>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=1000)
0.05842900276184082
>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=10000)
0.5394978523254395
>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=100000)
5.377126932144165
</code></pre>
<p>Here is the code:</p>
<pre><code>import os
def tail(f, lines=1, _buffer=4098):
"""Tail a file and get X lines from the end"""
# place holder for the lines found
lines_found = []
# block counter will be multiplied by buffer
# to get the block size from the end
block_counter = -1
# loop until we find X lines
while len(lines_found) < lines:
try:
f.seek(block_counter * _buffer, os.SEEK_END)
except IOError: # either file is too small, or too many lines requested
f.seek(0)
lines_found = f.readlines()
break
lines_found = f.readlines()
# we found enough lines, get out
if len(lines_found) > lines:
break
# decrement the block counter to get the
# next X bytes
block_counter -= 1
return lines_found[-lines:]
</code></pre>
| 10 | 2012-12-09T18:21:42Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 16,507,215 | <p>I had to read a specific value from the last line of a file, and stumbled upon this thread. Rather than reinventing the wheel in Python, I ended up with a tiny shell script, saved as
/usr/local/bin/get_last_netp:</p>
<pre><code>#! /bin/bash
tail -n1 /home/leif/projects/transfer/export.log | awk {'print $14'}
</code></pre>
<p>And in the Python program:</p>
<pre><code>from subprocess import check_output
last_netp = int(check_output("/usr/local/bin/get_last_netp"))
</code></pre>
| 1 | 2013-05-12T12:11:01Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 16,507,435 | <p>Not the first example using a deque, but a simpler one. This one is general: it works on any iterable object, not just a file.</p>
<pre><code>#!/usr/bin/env python
import sys
import collections
def tail(iterable, N):
deq = collections.deque()
for thing in iterable:
if len(deq) >= N:
deq.popleft()
deq.append(thing)
for thing in deq:
yield thing
if __name__ == '__main__':
for line in tail(sys.stdin,10):
sys.stdout.write(line)
</code></pre>
| 0 | 2013-05-12T12:38:55Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 23,290,416 | <pre><code>This is my version of tailf
import sys, time, os
filename = 'path to file'
try:
with open(filename) as f:
size = os.path.getsize(filename)
if size < 1024:
s = size
else:
s = 999
f.seek(-s, 2)
l = f.read()
print l
while True:
line = f.readline()
if not line:
time.sleep(1)
continue
print line
except IOError:
pass
</code></pre>
| 0 | 2014-04-25T10:24:36Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 25,450,971 | <pre><code>import time
attemps = 600
wait_sec = 5
fname = "YOUR_PATH"
with open(fname, "r") as f:
where = f.tell()
for i in range(attemps):
line = f.readline()
if not line:
time.sleep(wait_sec)
f.seek(where)
else:
print line, # already has newline
</code></pre>
| 0 | 2014-08-22T15:52:53Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 34,029,605 | <p>Posting an answer at the behest of commenters on <a href="/a/33811809/364696">my answer to a similar question</a> where the same technique was used to mutate the last line of a file, not just get it.</p>
<p>For a file of significant size, <a href="https://docs.python.org/3/library/mmap.html" rel="nofollow"><code>mmap</code></a> is the best way to do this. To improve on the existing <code>mmap</code> answer, this version is portable between Windows and Linux, and should run faster (though it won't work without some modifications on 32 bit Python with files in the GB range, see the <a href="/a/33811809/364696">other answer for hints on handling this, and for modifying to work on Python 2</a>).</p>
<pre><code>import io # Gets consistent version of open for both Py2.7 and Py3.x
import itertools
import mmap
def skip_back_lines(mm, numlines, startidx):
'''Factored out to simplify handling of n and offset'''
for _ in itertools.repeat(None, numlines):
startidx= mm.rfind(b'\n', 0, startidx)
if startidx< 0:
break
return startidx
def tail(f, n, offset=0):
# Reopen file in binary mode
with io.open(f.name, 'rb') as binf, mmap.mmap(binf.fileno(), 0, access=mmap.ACCESS_READ) as mm:
# len(mm) - 1 handles files ending w/newline by getting the prior line
startofline = skip_back_lines(mm, offset, len(mm) - 1)
if startofline < 0:
return [] # Offset lines consumed whole file, nothing to return
# If using a generator function (yield-ing, see below),
# this should be a plain return, no empty list
endoflines = startofline + 1 # Slice end to omit offset lines
# Find start of lines to capture (add 1 to move from newline to beginning of following line)
startofline = skip_back_lines(mm, n, startofline) + 1
# Passing True to splitlines makes it return the list of lines without
# removing the trailing newline (if any), so list mimics f.readlines()
return mm[startofline:endoflines].splitlines(True)
# If Windows style \r\n newlines need to be normalized to \n, and input
# is ASCII compatible, can normalize newlines with:
# return mm[startofline:endoflines].replace(os.linesep.encode('ascii'), b'\n').splitlines(True)
</code></pre>
<p>This assumes the number of lines tailed is small enough you can safely read them all into memory at once; you could also make this a generator function and manually read a line at a time by replacing the final line with:</p>
<pre><code> mm.seek(startofline)
# Call mm.readline n times, or until EOF, whichever comes first
for line in itertools.islice(iter(mm.readline, b''), n):
yield line
</code></pre>
<p>Lastly, this read in binary mode (necessary to use <code>mmap</code>) so it gives <code>str</code> lines (Py2) and <code>bytes</code> lines (Py3); if you want <code>unicode</code> (Py2) or <code>str</code> (Py3), the iterative approach could be tweaked to decode for you and/or fix newlines:</p>
<pre><code> lines = itertools.islice(iter(mm.readline, b''), n)
if f.encoding: # Decode if the passed file was opened with a specific encoding
lines = (line.decode(f.encoding) for line in lines)
if 'b' not in f.mode: # Fix line breaks if passed file opened in text mode
lines = (line.replace(os.linesep, '\n') for line in lines)
for line in lines:
yield line
</code></pre>
<p>Note: I typed this all up on a machine where I lack access to Python to test. Please let me know if I typoed anything; this was similar enough to <a href="/a/33811809/364696">my other answer</a> that I <em>think</em> it should work, but the tweaks (e.g. handling an <code>offset</code>) could lead to subtle errors. Please let me know in the comments if there are any mistakes.</p>
| 2 | 2015-12-01T20:34:50Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 37,176,501 | <p>Although this isn't really on the efficient side with big files, this code is pretty straight-forward:<br></p>
<ol>
<li>It reads the file object, <code>f</code>.</li>
<li>It splits the string returned using newlines, <code>\n</code>.</li>
<li><p>It gets the array lists last indexes, using the negative sign to stand for the last indexes, and the <code>:</code> to get a subarray.<br><br></p>
<pre><code>def tail(f,n):
return "\n".join(f.read().split("\n")[-n:])
</code></pre></li>
</ol>
| 0 | 2016-05-12T02:57:48Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 37,903,261 | <p>Here is a pretty simple implementation:</p>
<pre><code>with open('/etc/passwd', 'r') as f:
try:
f.seek(0,2)
s = ''
while s.count('\n') < 11:
cur = f.tell()
f.seek((cur - 10))
s = f.read(10) + s
f.seek((cur - 10))
print s
except Exception as e:
f.readlines()
</code></pre>
| 0 | 2016-06-19T01:54:08Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
How do you manage your custom modules? | 136,207 | <p>I write tons of python scripts, and I find myself reusing lots code that I've written for other projects. My solution has been to make sure the code is separated into logical modules/packages (this one's a given). I then make them setuptools-aware and publish them on PyPI. This allows my other scripts to always have the most up-to-date code, I get a warm fuzzy feeling because I'm not repeating myself, and my development, in general, is made less complicated. I also feel good that there MAY be someone out there that finds my code handy for something they're working on, but it's mainly for selfish reasons :)</p>
<p>To all the pythonistas, how do you handle this? Do you use PyPI or setuptools (easy_install)? or something else?</p>
| 10 | 2008-09-25T21:18:09Z | 137,052 | <p>I have been doing the same thing. Extract common functionality, pretty the code up with extra documentation and unit tests/ doctests, create an easy_install setup.py, and then release on PyPi. Recently, I created a single <a href="http://code.google.com/p/7oars/" rel="nofollow">Google Code site</a> where I manage the source and keep the wiki up to date. </p>
| 1 | 2008-09-26T00:13:02Z | [
"python",
"code-reuse"
] |
How do you manage your custom modules? | 136,207 | <p>I write tons of python scripts, and I find myself reusing lots code that I've written for other projects. My solution has been to make sure the code is separated into logical modules/packages (this one's a given). I then make them setuptools-aware and publish them on PyPI. This allows my other scripts to always have the most up-to-date code, I get a warm fuzzy feeling because I'm not repeating myself, and my development, in general, is made less complicated. I also feel good that there MAY be someone out there that finds my code handy for something they're working on, but it's mainly for selfish reasons :)</p>
<p>To all the pythonistas, how do you handle this? Do you use PyPI or setuptools (easy_install)? or something else?</p>
| 10 | 2008-09-25T21:18:09Z | 137,291 | <p>What kind of modules are we talking about here? If you're planning on distributing your projects to other python developers, setuptools is great. But it's usually not a very good way to distribute apps to end users. Your best bet in the latter case is to tailor your packaging to the platforms you're distributing it for. Sure, it's a pain, but it makes life for end users far easier.</p>
<p>For example, in my Debian system, I usually don't use easy_install because it is a little bit more difficult to get eggs to work well with the package manager. In OS X and windows, you'd probably want to package everything up using py2app and py2exe respectively. This makes life for the end user better. After all, they shouldn't know or care what language your scripts are written in. They just need them to install.</p>
| 1 | 2008-09-26T01:39:58Z | [
"python",
"code-reuse"
] |
Key Presses in Python | 136,734 | <p>Is it possible to make it appear to a system that a key was pressed, for example I need to make <kbd>A</kbd> key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.</p>
<p>A better way to put it, I need to emulate a key press, I.E. not capture a key press.</p>
<p>More Info (as requested):
I am running windows XP and need to send the keys to another application.</p>
| 13 | 2008-09-25T22:58:01Z | 136,741 | <p>It's probably <em>possible</em> - but where do you want the key presses to go? To another application? That would probably be a case of understanding your platform's windowing toolkit and sending the right messages to the right window.</p>
<p>Clarify your requirements, and I'm sure we can help out.</p>
| 0 | 2008-09-25T22:59:55Z | [
"python",
"keypress"
] |
Key Presses in Python | 136,734 | <p>Is it possible to make it appear to a system that a key was pressed, for example I need to make <kbd>A</kbd> key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.</p>
<p>A better way to put it, I need to emulate a key press, I.E. not capture a key press.</p>
<p>More Info (as requested):
I am running windows XP and need to send the keys to another application.</p>
| 13 | 2008-09-25T22:58:01Z | 136,759 | <p><a href="http://www.autohotkey.com/" rel="nofollow">AutoHotKey</a> is perfect for this kind of tasks (keyboard automation / remapping)</p>
<p>Script to send "A" 100 times:</p>
<pre><code>Send {A 100}
</code></pre>
<p>That's all</p>
<p><strong>EDIT</strong>: to send the keys to an specific application:</p>
<pre><code>WinActivate Word
Send {A 100}
</code></pre>
| 5 | 2008-09-25T23:03:55Z | [
"python",
"keypress"
] |
Key Presses in Python | 136,734 | <p>Is it possible to make it appear to a system that a key was pressed, for example I need to make <kbd>A</kbd> key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.</p>
<p>A better way to put it, I need to emulate a key press, I.E. not capture a key press.</p>
<p>More Info (as requested):
I am running windows XP and need to send the keys to another application.</p>
| 13 | 2008-09-25T22:58:01Z | 136,780 | <p>Install the <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a> extensions. Then you can do the following:</p>
<pre><code>import win32com.client as comclt
wsh= comclt.Dispatch("WScript.Shell")
wsh.AppActivate("Notepad") # select another application
wsh.SendKeys("a") # send the keys you want
</code></pre>
<p>Search for documentation of the WScript.Shell object (I believe installed by default in all Windows XP installations). You can start <a href="http://www.microsoft.com/technet/scriptcenter/guide/sas_wsh_pkoy.mspx?mfr=true" rel="nofollow">here</a>, perhaps.</p>
<p><strong>EDIT:</strong> Sending F11 </p>
<pre><code>import win32com.client as comctl
wsh = comctl.Dispatch("WScript.Shell")
# Google Chrome window title
wsh.AppActivate("icanhazip.com")
wsh.SendKeys("{F11}")
</code></pre>
| 17 | 2008-09-25T23:09:39Z | [
"python",
"keypress"
] |
Key Presses in Python | 136,734 | <p>Is it possible to make it appear to a system that a key was pressed, for example I need to make <kbd>A</kbd> key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.</p>
<p>A better way to put it, I need to emulate a key press, I.E. not capture a key press.</p>
<p>More Info (as requested):
I am running windows XP and need to send the keys to another application.</p>
| 13 | 2008-09-25T22:58:01Z | 136,786 | <p>If you're platform is Windows, I wouldn't actually recommend Python. Instead, look into <a href="http://www.autohotkey.com/" rel="nofollow">Autohotkey</a>. Trust me, I love Python, but in this circumstance a macro program is the ideal tool for the job. Autohotkey's scripting is only decent (in my opinion), but the ease of simulating input will save you countless hours. Autohotkey scripts can be "compiled" as well so you don't need the interpreter to run the script.</p>
<p>Also, if this is for something on the Web, I recommend <a href="https://addons.mozilla.org/en-US/firefox/addon/3863" rel="nofollow">iMacros</a>. It's a firefox plugin and therefore has a much better integration with websites. For example, you can say "write 1000 'a's in this form" instead of "simulate a mouseclick at (319,400) and then press 'a' 1000 times".</p>
<p>For Linux, I unfortunately have not been able to find a good way to easily create keyboard/mouse macros.</p>
| -1 | 2008-09-25T23:12:13Z | [
"python",
"keypress"
] |
Key Presses in Python | 136,734 | <p>Is it possible to make it appear to a system that a key was pressed, for example I need to make <kbd>A</kbd> key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.</p>
<p>A better way to put it, I need to emulate a key press, I.E. not capture a key press.</p>
<p>More Info (as requested):
I am running windows XP and need to send the keys to another application.</p>
| 13 | 2008-09-25T22:58:01Z | 1,282,600 | <p>Alternative way to set prefer window into foreground before send key press event.</p>
<pre><code>hwnd = win32gui.FindWindowEx(0,0,0, "App title")
win32gui.SetForegroundWindow(hwnd)
</code></pre>
| 0 | 2009-08-15T19:16:47Z | [
"python",
"keypress"
] |
Key Presses in Python | 136,734 | <p>Is it possible to make it appear to a system that a key was pressed, for example I need to make <kbd>A</kbd> key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.</p>
<p>A better way to put it, I need to emulate a key press, I.E. not capture a key press.</p>
<p>More Info (as requested):
I am running windows XP and need to send the keys to another application.</p>
| 13 | 2008-09-25T22:58:01Z | 33,249,229 | <p>You could also use PyAutoGui to send a virtual key presses.</p>
<p>Here's the documentation: <a href="https://pyautogui.readthedocs.org/en/latest/" rel="nofollow">https://pyautogui.readthedocs.org/en/latest/</a></p>
<pre><code>import pyautogui
pyautogui.keypress('Any key combination')
</code></pre>
<p>You can also send keys like the shift key or enter key with:</p>
<pre><code>import pyautogui
pyautogui.keypress('shift')
</code></pre>
<p>Pyautogui can also send straight text like so:</p>
<pre><code>import pyautogui
pyautogui.typewrite('any text you want to type')
</code></pre>
| 3 | 2015-10-21T00:57:43Z | [
"python",
"keypress"
] |
Python language API | 136,739 | <p>I'm starting with Python coming from java. </p>
<p>I was wondering if there exists something similar to JavaDoc API where I can find the class, its methods and and example of how to use it.</p>
<p>I've found very helpul to use <em>help( thing )</em> from the Python ( command line ) </p>
<p>I have found this also:</p>
<p><a href="http://docs.python.org/2/" rel="nofollow">http://docs.python.org/2/</a></p>
<p><a href="https://docs.python.org/2/py-modindex.html" rel="nofollow">https://docs.python.org/2/py-modindex.html</a></p>
<p>But it seems to help when you already have the class name you are looking for. In JavaDoc API I have all the classes so if I need something I scroll down to a class that "sounds like" what I need. Or some times I just browse all the classes to see what they do, and when I need a feature my brain recalls me <em>We saw something similar in the javadoc remember!?</em> </p>
<p>But I don't seem to find the similar in Python ( yet ) and that why I'm posting this questin. </p>
<p>BTW I know that I would eventually will read this:</p>
<p><a href="https://docs.python.org/2/library/" rel="nofollow">https://docs.python.org/2/library/</a></p>
<p>But, well, I think it is not today.</p>
| 6 | 2008-09-25T22:59:10Z | 136,749 | <p><a href="http://docs.python.org/library/pydoc.html" rel="nofollow">pydoc</a>?</p>
<p>I'm not sure if you're looking for something more sophisticated, but it does the trick.</p>
| 5 | 2008-09-25T23:00:48Z | [
"python",
"reference",
"documentation",
"python-2.x"
] |
Python language API | 136,739 | <p>I'm starting with Python coming from java. </p>
<p>I was wondering if there exists something similar to JavaDoc API where I can find the class, its methods and and example of how to use it.</p>
<p>I've found very helpul to use <em>help( thing )</em> from the Python ( command line ) </p>
<p>I have found this also:</p>
<p><a href="http://docs.python.org/2/" rel="nofollow">http://docs.python.org/2/</a></p>
<p><a href="https://docs.python.org/2/py-modindex.html" rel="nofollow">https://docs.python.org/2/py-modindex.html</a></p>
<p>But it seems to help when you already have the class name you are looking for. In JavaDoc API I have all the classes so if I need something I scroll down to a class that "sounds like" what I need. Or some times I just browse all the classes to see what they do, and when I need a feature my brain recalls me <em>We saw something similar in the javadoc remember!?</em> </p>
<p>But I don't seem to find the similar in Python ( yet ) and that why I'm posting this questin. </p>
<p>BTW I know that I would eventually will read this:</p>
<p><a href="https://docs.python.org/2/library/" rel="nofollow">https://docs.python.org/2/library/</a></p>
<p>But, well, I think it is not today.</p>
| 6 | 2008-09-25T22:59:10Z | 136,758 | <p><a href="https://docs.python.org/py-modindex.html" rel="nofollow">Here</a> is a list of all the modules in Python, not sure if that's what you're really after.</p>
| 1 | 2008-09-25T23:03:33Z | [
"python",
"reference",
"documentation",
"python-2.x"
] |
Python language API | 136,739 | <p>I'm starting with Python coming from java. </p>
<p>I was wondering if there exists something similar to JavaDoc API where I can find the class, its methods and and example of how to use it.</p>
<p>I've found very helpul to use <em>help( thing )</em> from the Python ( command line ) </p>
<p>I have found this also:</p>
<p><a href="http://docs.python.org/2/" rel="nofollow">http://docs.python.org/2/</a></p>
<p><a href="https://docs.python.org/2/py-modindex.html" rel="nofollow">https://docs.python.org/2/py-modindex.html</a></p>
<p>But it seems to help when you already have the class name you are looking for. In JavaDoc API I have all the classes so if I need something I scroll down to a class that "sounds like" what I need. Or some times I just browse all the classes to see what they do, and when I need a feature my brain recalls me <em>We saw something similar in the javadoc remember!?</em> </p>
<p>But I don't seem to find the similar in Python ( yet ) and that why I'm posting this questin. </p>
<p>BTW I know that I would eventually will read this:</p>
<p><a href="https://docs.python.org/2/library/" rel="nofollow">https://docs.python.org/2/library/</a></p>
<p>But, well, I think it is not today.</p>
| 6 | 2008-09-25T22:59:10Z | 136,760 | <p>If you're working on Windows <a href="http://www.activestate.com/Products/activepython/index.mhtml" rel="nofollow">ActiveState Python</a> comes with the documentation, including the library reference in a searchable help file.</p>
| 0 | 2008-09-25T23:04:21Z | [
"python",
"reference",
"documentation",
"python-2.x"
] |
Python language API | 136,739 | <p>I'm starting with Python coming from java. </p>
<p>I was wondering if there exists something similar to JavaDoc API where I can find the class, its methods and and example of how to use it.</p>
<p>I've found very helpul to use <em>help( thing )</em> from the Python ( command line ) </p>
<p>I have found this also:</p>
<p><a href="http://docs.python.org/2/" rel="nofollow">http://docs.python.org/2/</a></p>
<p><a href="https://docs.python.org/2/py-modindex.html" rel="nofollow">https://docs.python.org/2/py-modindex.html</a></p>
<p>But it seems to help when you already have the class name you are looking for. In JavaDoc API I have all the classes so if I need something I scroll down to a class that "sounds like" what I need. Or some times I just browse all the classes to see what they do, and when I need a feature my brain recalls me <em>We saw something similar in the javadoc remember!?</em> </p>
<p>But I don't seem to find the similar in Python ( yet ) and that why I'm posting this questin. </p>
<p>BTW I know that I would eventually will read this:</p>
<p><a href="https://docs.python.org/2/library/" rel="nofollow">https://docs.python.org/2/library/</a></p>
<p>But, well, I think it is not today.</p>
| 6 | 2008-09-25T22:59:10Z | 136,783 | <p>The standard python library is fairly well documented. Try jumping into python and importing a module say "os" and running:</p>
<pre><code>import os
help(os)
</code></pre>
<p>This reads the doc strings on each of the items in the module and displays it. This is exactly what pydoc will do too.</p>
<p>EDIT: <a href="http://epydoc.sourceforge.net/" rel="nofollow">epydoc</a> is probably exactly what you're looking for: </p>
| 2 | 2008-09-25T23:11:13Z | [
"python",
"reference",
"documentation",
"python-2.x"
] |
Python language API | 136,739 | <p>I'm starting with Python coming from java. </p>
<p>I was wondering if there exists something similar to JavaDoc API where I can find the class, its methods and and example of how to use it.</p>
<p>I've found very helpul to use <em>help( thing )</em> from the Python ( command line ) </p>
<p>I have found this also:</p>
<p><a href="http://docs.python.org/2/" rel="nofollow">http://docs.python.org/2/</a></p>
<p><a href="https://docs.python.org/2/py-modindex.html" rel="nofollow">https://docs.python.org/2/py-modindex.html</a></p>
<p>But it seems to help when you already have the class name you are looking for. In JavaDoc API I have all the classes so if I need something I scroll down to a class that "sounds like" what I need. Or some times I just browse all the classes to see what they do, and when I need a feature my brain recalls me <em>We saw something similar in the javadoc remember!?</em> </p>
<p>But I don't seem to find the similar in Python ( yet ) and that why I'm posting this questin. </p>
<p>BTW I know that I would eventually will read this:</p>
<p><a href="https://docs.python.org/2/library/" rel="nofollow">https://docs.python.org/2/library/</a></p>
<p>But, well, I think it is not today.</p>
| 6 | 2008-09-25T22:59:10Z | 136,929 | <p>I've downloaded Python 2.5 from Python.org and It does not contains pydoc.</p>
<pre><code>Directorio de C:\Python25
9/23/2008 10:45 PM <DIR> .
9/23/2008 10:45 PM <DIR> ..
9/23/2008 10:45 PM <DIR> DLLs
9/23/2008 10:45 PM <DIR> Doc
9/23/2008 10:45 PM <DIR> include
9/25/2008 06:34 PM <DIR> Lib
9/23/2008 10:45 PM <DIR> libs
2/21/2008 01:05 PM 14,013 LICENSE.txt
2/21/2008 01:05 PM 119,048 NEWS.txt
2/21/2008 01:11 PM 24,064 python.exe
2/21/2008 01:12 PM 24,576 pythonw.exe
2/21/2008 01:05 PM 56,354 README.txt
9/23/2008 10:45 PM <DIR> tcl
9/23/2008 10:45 PM <DIR> Tools
2/21/2008 01:11 PM 4,608 w9xpopen.exe
6 archivos 242,663 bytes
</code></pre>
<p>But it has ( the substitute I guess ) pydocgui...</p>
<pre><code>C:\Python25>dir Tools\Scripts\pydocgui.pyw
10/28/2005 07:06 PM 222 pydocgui.pyw
1 archivos 222 bytes
</code></pre>
<p>This launches a webserver and shows what I was looking for. All the modules plus all the classes that come with the platform.</p>
<p>The Doc dir contains the same as in:</p>
<p><a href="http://docs.python.org/" rel="nofollow">http://docs.python.org/</a></p>
<p>Thanks a lot for guide me to pydoc.</p>
| 1 | 2008-09-25T23:42:37Z | [
"python",
"reference",
"documentation",
"python-2.x"
] |
Python language API | 136,739 | <p>I'm starting with Python coming from java. </p>
<p>I was wondering if there exists something similar to JavaDoc API where I can find the class, its methods and and example of how to use it.</p>
<p>I've found very helpul to use <em>help( thing )</em> from the Python ( command line ) </p>
<p>I have found this also:</p>
<p><a href="http://docs.python.org/2/" rel="nofollow">http://docs.python.org/2/</a></p>
<p><a href="https://docs.python.org/2/py-modindex.html" rel="nofollow">https://docs.python.org/2/py-modindex.html</a></p>
<p>But it seems to help when you already have the class name you are looking for. In JavaDoc API I have all the classes so if I need something I scroll down to a class that "sounds like" what I need. Or some times I just browse all the classes to see what they do, and when I need a feature my brain recalls me <em>We saw something similar in the javadoc remember!?</em> </p>
<p>But I don't seem to find the similar in Python ( yet ) and that why I'm posting this questin. </p>
<p>BTW I know that I would eventually will read this:</p>
<p><a href="https://docs.python.org/2/library/" rel="nofollow">https://docs.python.org/2/library/</a></p>
<p>But, well, I think it is not today.</p>
| 6 | 2008-09-25T22:59:10Z | 137,335 | <blockquote>
<p>BTW I know that I would eventually
will read this:</p>
<p><a href="http://docs.python.org/lib/lib.html" rel="nofollow">http://docs.python.org/lib/lib.html</a></p>
<p>But, well, I think it is not today.</p>
</blockquote>
<p>I suggest that you're making a mistake. The lib doc has "the class, its methods and and example of how to use it." It <em>is</em> what you are looking for. </p>
<p>I use both Java and Python all the time. Dig into the library doc, you'll find everything you're looking for.</p>
| 1 | 2008-09-26T01:56:12Z | [
"python",
"reference",
"documentation",
"python-2.x"
] |
Python language API | 136,739 | <p>I'm starting with Python coming from java. </p>
<p>I was wondering if there exists something similar to JavaDoc API where I can find the class, its methods and and example of how to use it.</p>
<p>I've found very helpul to use <em>help( thing )</em> from the Python ( command line ) </p>
<p>I have found this also:</p>
<p><a href="http://docs.python.org/2/" rel="nofollow">http://docs.python.org/2/</a></p>
<p><a href="https://docs.python.org/2/py-modindex.html" rel="nofollow">https://docs.python.org/2/py-modindex.html</a></p>
<p>But it seems to help when you already have the class name you are looking for. In JavaDoc API I have all the classes so if I need something I scroll down to a class that "sounds like" what I need. Or some times I just browse all the classes to see what they do, and when I need a feature my brain recalls me <em>We saw something similar in the javadoc remember!?</em> </p>
<p>But I don't seem to find the similar in Python ( yet ) and that why I'm posting this questin. </p>
<p>BTW I know that I would eventually will read this:</p>
<p><a href="https://docs.python.org/2/library/" rel="nofollow">https://docs.python.org/2/library/</a></p>
<p>But, well, I think it is not today.</p>
| 6 | 2008-09-25T22:59:10Z | 138,121 | <p>It doesn't directly answer your question (so I'll probably be downgraded), but you may be interested in <a href="http://www.jython.org" rel="nofollow">Jython</a>.</p>
<blockquote>
<p>Jython is an implementation of the high-level, dynamic, object-oriented language Python written in 100% Pure Java, and seamlessly integrated with the Java platform. It thus allows you to run Python on any Java platform.</p>
</blockquote>
<p>Since you are coming from Java, Jython may help you leverage Python while still allowing you to use your Java knowledge.</p>
| 0 | 2008-09-26T07:16:09Z | [
"python",
"reference",
"documentation",
"python-2.x"
] |
Python language API | 136,739 | <p>I'm starting with Python coming from java. </p>
<p>I was wondering if there exists something similar to JavaDoc API where I can find the class, its methods and and example of how to use it.</p>
<p>I've found very helpul to use <em>help( thing )</em> from the Python ( command line ) </p>
<p>I have found this also:</p>
<p><a href="http://docs.python.org/2/" rel="nofollow">http://docs.python.org/2/</a></p>
<p><a href="https://docs.python.org/2/py-modindex.html" rel="nofollow">https://docs.python.org/2/py-modindex.html</a></p>
<p>But it seems to help when you already have the class name you are looking for. In JavaDoc API I have all the classes so if I need something I scroll down to a class that "sounds like" what I need. Or some times I just browse all the classes to see what they do, and when I need a feature my brain recalls me <em>We saw something similar in the javadoc remember!?</em> </p>
<p>But I don't seem to find the similar in Python ( yet ) and that why I'm posting this questin. </p>
<p>BTW I know that I would eventually will read this:</p>
<p><a href="https://docs.python.org/2/library/" rel="nofollow">https://docs.python.org/2/library/</a></p>
<p>But, well, I think it is not today.</p>
| 6 | 2008-09-25T22:59:10Z | 138,240 | <p>You can set the <em>environment variable</em> <strong>PYTHONDOCS</strong> to point to where the python documentation is installed.</p>
<p>On my system, it's in <em>/usr/share/doc/python2.5</em></p>
<p>So you can define this variable in your <em>shell profile</em> or somewhere else depending on your system:</p>
<blockquote>
<p>export PYTHONDOCS=/usr/share/doc/python2.5</p>
</blockquote>
<p>Now, if you open an interractive python console, you can call the help system. For exemple:</p>
<blockquote>
<pre><code>>>> help(Exception)
>>> Help on class Exception in module exceptions:
>>> class Exception(BaseException)
>>> | Common base class for all non-exit exceptions.
>>> |
>>> | Method resolution order:
>>> | Exception
</code></pre>
</blockquote>
<p>Documentation is here:</p>
<p><a href="https://docs.python.org/library/pydoc.html" rel="nofollow">https://docs.python.org/library/pydoc.html</a></p>
| 1 | 2008-09-26T08:07:29Z | [
"python",
"reference",
"documentation",
"python-2.x"
] |
Python language API | 136,739 | <p>I'm starting with Python coming from java. </p>
<p>I was wondering if there exists something similar to JavaDoc API where I can find the class, its methods and and example of how to use it.</p>
<p>I've found very helpul to use <em>help( thing )</em> from the Python ( command line ) </p>
<p>I have found this also:</p>
<p><a href="http://docs.python.org/2/" rel="nofollow">http://docs.python.org/2/</a></p>
<p><a href="https://docs.python.org/2/py-modindex.html" rel="nofollow">https://docs.python.org/2/py-modindex.html</a></p>
<p>But it seems to help when you already have the class name you are looking for. In JavaDoc API I have all the classes so if I need something I scroll down to a class that "sounds like" what I need. Or some times I just browse all the classes to see what they do, and when I need a feature my brain recalls me <em>We saw something similar in the javadoc remember!?</em> </p>
<p>But I don't seem to find the similar in Python ( yet ) and that why I'm posting this questin. </p>
<p>BTW I know that I would eventually will read this:</p>
<p><a href="https://docs.python.org/2/library/" rel="nofollow">https://docs.python.org/2/library/</a></p>
<p>But, well, I think it is not today.</p>
| 6 | 2008-09-25T22:59:10Z | 138,317 | <p>Also try</p>
<pre><code>pydoc -p 11111
</code></pre>
<p>Then type in web browser <a href="http://localhost:11111" rel="nofollow">http://localhost:11111</a></p>
<p>EDIT: of course you can use any other value for port number instead of 11111</p>
| 0 | 2008-09-26T08:34:18Z | [
"python",
"reference",
"documentation",
"python-2.x"
] |
How do you make Python / PostgreSQL faster? | 136,789 | <p>Right now I have a log parser reading through 515mb of plain-text files (a file for each day over the past 4 years). My code currently stands as this: <a href="http://gist.github.com/12978" rel="nofollow">http://gist.github.com/12978</a>. I've used psyco (as seen in the code) and I'm also compiling it and using the compiled version. It's doing about 100 lines every 0.3 seconds. The machine is a standard 15" MacBook Pro (2.4ghz C2D, 2GB RAM)</p>
<p>Is it possible for this to go faster or is that a limitation on the language/database?</p>
| 4 | 2008-09-25T23:12:50Z | 136,870 | <p>Use bind variables instead of literal values in the sql statements and create a cursor for
each unique sql statement so that the statement does not need to be reparsed the next time it is used. From the python db api doc:</p>
<blockquote>
<p>Prepare and execute a database
operation (query or command).
Parameters may be provided as sequence
or mapping and will be bound to
variables in the operation. Variables
are specified in a database-specific
notation (see the module's paramstyle
attribute for details). [5]</p>
<p>A reference to the operation will be
retained by the cursor. If the same
operation object is passed in again,
then the cursor can optimize its
behavior. This is most effective for
algorithms where the same operation is
used, but different parameters are
bound to it (many times).</p>
</blockquote>
<p>ALWAYS ALWAYS ALWAYS use bind variables.</p>
| 3 | 2008-09-25T23:29:56Z | [
"python",
"postgresql"
] |
How do you make Python / PostgreSQL faster? | 136,789 | <p>Right now I have a log parser reading through 515mb of plain-text files (a file for each day over the past 4 years). My code currently stands as this: <a href="http://gist.github.com/12978" rel="nofollow">http://gist.github.com/12978</a>. I've used psyco (as seen in the code) and I'm also compiling it and using the compiled version. It's doing about 100 lines every 0.3 seconds. The machine is a standard 15" MacBook Pro (2.4ghz C2D, 2GB RAM)</p>
<p>Is it possible for this to go faster or is that a limitation on the language/database?</p>
| 4 | 2008-09-25T23:12:50Z | 137,002 | <p>In the for loop, you're inserting into the 'chats' table repeatedly, so you only need a single sql statement with bind variables, to be executed with different values. So you could put this before the for loop:</p>
<pre><code>insert_statement="""
INSERT INTO chats(person_id, message_type, created_at, channel)
VALUES(:person_id,:message_type,:created_at,:channel)
"""
</code></pre>
<p>Then in place of each sql statement you execute put this in place:</p>
<pre><code>cursor.execute(insert_statement, person_id='person',message_type='msg',created_at=some_date, channel=3)
</code></pre>
<p>This will make things run faster because:</p>
<ol>
<li>The cursor object won't have to reparse the statement each time</li>
<li>The db server won't have to generate a new execution plan as it can use the one it create previously.</li>
<li>You won't have to call santitize() as special characters in the bind variables won't part of the sql statement that gets executed.</li>
</ol>
<p>Note: The bind variable syntax I used is Oracle specific. You'll have to check the psycopg2 library's documentation for the exact syntax.</p>
<p>Other optimizations:</p>
<ol>
<li>You're incrementing with the "UPDATE people SET chatscount" after each loop iteration. Keep a dictionary mapping user to chat_count and then execute the statement of the total number you've seen. This will be faster then hitting the db after every record.</li>
<li>Use bind variables on ALL your queries. Not just the insert statement, I choose that as an example.</li>
<li>Change all the find_*() functions that do db look ups to cache their results so they don't have to hit the db every time.</li>
<li>psycho optimizes python programs that perform a large number of numberic operation. The script is IO expensive and not CPU expensive so I wouldn't expect to give you much if any optimization.</li>
</ol>
| 3 | 2008-09-25T23:59:39Z | [
"python",
"postgresql"
] |
How do you make Python / PostgreSQL faster? | 136,789 | <p>Right now I have a log parser reading through 515mb of plain-text files (a file for each day over the past 4 years). My code currently stands as this: <a href="http://gist.github.com/12978" rel="nofollow">http://gist.github.com/12978</a>. I've used psyco (as seen in the code) and I'm also compiling it and using the compiled version. It's doing about 100 lines every 0.3 seconds. The machine is a standard 15" MacBook Pro (2.4ghz C2D, 2GB RAM)</p>
<p>Is it possible for this to go faster or is that a limitation on the language/database?</p>
| 4 | 2008-09-25T23:12:50Z | 137,076 | <p>As Mark suggested, use binding variables. The database only has to prepare each statement once, then "fill in the blanks" for each execution. As a nice side effect, it will automatically take care of string-quoting issues (which your program isn't handling).</p>
<p>Turn transactions on (if they aren't already) and do a single commit at the end of the program. The database won't have to write anything to disk until all the data needs to be committed. And if your program encounters an error, none of the rows will be committed, allowing you to simply re-run the program once the problem has been corrected.</p>
<p>Your log_hostname, log_person, and log_date functions are doing needless SELECTs on the tables. Make the appropriate table attributes PRIMARY KEY or UNIQUE. Then, instead of checking for the presence of the key before you INSERT, just do the INSERT. If the person/date/hostname already exists, the INSERT will fail from the constraint violation. (This won't work if you use a transaction with a single commit, as suggested above.)</p>
<p>Alternatively, if you know you're the only one INSERTing into the tables while your program is running, then create parallel data structures in memory and maintain them in memory while you do your INSERTs. For example, read in all the hostnames from the table into an associative array at the start of the program. When want to know whether to do an INSERT, just do an array lookup. If no entry found, do the INSERT and update the array appropriately. (This suggestion is compatible with transactions and a single commit, but requires more programming. It'll be wickedly faster, though.)</p>
| 2 | 2008-09-26T00:20:36Z | [
"python",
"postgresql"
] |
How do you make Python / PostgreSQL faster? | 136,789 | <p>Right now I have a log parser reading through 515mb of plain-text files (a file for each day over the past 4 years). My code currently stands as this: <a href="http://gist.github.com/12978" rel="nofollow">http://gist.github.com/12978</a>. I've used psyco (as seen in the code) and I'm also compiling it and using the compiled version. It's doing about 100 lines every 0.3 seconds. The machine is a standard 15" MacBook Pro (2.4ghz C2D, 2GB RAM)</p>
<p>Is it possible for this to go faster or is that a limitation on the language/database?</p>
| 4 | 2008-09-25T23:12:50Z | 137,096 | <p>Additionally to the many fine suggestions @Mark Roddy has given, do the following:</p>
<ul>
<li>don't use <code>readlines</code>, you can iterate over file objects</li>
<li>try to use <code>executemany</code> rather than <code>execute</code>: try to do batch inserts rather single inserts, this tends to be faster because there's less overhead. It also reduces the number of commits</li>
<li><code>str.rstrip</code> will work just fine instead of stripping of the newline with a regex</li>
</ul>
<p>Batching the inserts will use more memory temporarily, but that should be fine when you don't read the whole file into memory.</p>
| 1 | 2008-09-26T00:26:21Z | [
"python",
"postgresql"
] |
How do you make Python / PostgreSQL faster? | 136,789 | <p>Right now I have a log parser reading through 515mb of plain-text files (a file for each day over the past 4 years). My code currently stands as this: <a href="http://gist.github.com/12978" rel="nofollow">http://gist.github.com/12978</a>. I've used psyco (as seen in the code) and I'm also compiling it and using the compiled version. It's doing about 100 lines every 0.3 seconds. The machine is a standard 15" MacBook Pro (2.4ghz C2D, 2GB RAM)</p>
<p>Is it possible for this to go faster or is that a limitation on the language/database?</p>
| 4 | 2008-09-25T23:12:50Z | 137,320 | <p>Don't waste time profiling. The time is always in the database operations. Do as few as possible. Just the minimum number of inserts.</p>
<p>Three Things.</p>
<p>One. Don't SELECT over and over again to conform the Date, Hostname and Person dimensions. Fetch all the data ONCE into a Python dictionary and use it in memory. Don't do repeated singleton selects. Use Python.</p>
<p>Two. Don't Update.</p>
<p>Specifically, Do not do this. It's bad code for two reasons.</p>
<pre><code>cursor.execute("UPDATE people SET chats_count = chats_count + 1 WHERE id = '%s'" % person_id)
</code></pre>
<p>It be replaced with a simple SELECT COUNT(*) FROM ... . Never update to increment a count. Just count the rows that are there with a SELECT statement. [If you can't do this with a simple SELECT COUNT or SELECT COUNT(DISTINCT), you're missing some data -- your data model should always provide correct complete counts. Never update.]</p>
<p>And. Never build SQL using string substitution. Completely dumb.</p>
<p>If, for some reason the <code>SELECT COUNT(*)</code> isn't fast enough (benchmark first, before doing anything lame) you can cache the result of the count in another table. AFTER all of the loads. Do a <code>SELECT COUNT(*) FROM whatever GROUP BY whatever</code> and insert this into a table of counts. Don't Update. Ever.</p>
<p>Three. Use Bind Variables. Always.</p>
<pre><code>cursor.execute( "INSERT INTO ... VALUES( %(x)s, %(y)s, %(z)s )", {'x':person_id, 'y':time_to_string(time), 'z':channel,} )
</code></pre>
<p>The SQL never changes. The values bound in change, but the SQL never changes. This is MUCH faster. Never build SQL statements dynamically. Never. </p>
| 5 | 2008-09-26T01:50:23Z | [
"python",
"postgresql"
] |
How can I perform a HEAD request with the mechanize library? | 137,580 | <p>I know how to do a HEAD request with httplib, but I have to use mechanize for this site. </p>
<p>Essentially, what I need to do is grab a value from the header (filename) without actually downloading the file.</p>
<p>Any suggestions how I could accomplish this?</p>
| 3 | 2008-09-26T03:20:19Z | 137,624 | <p>Mechanize itself only sends GETs and POSTs, but you can easily extend the Request class to send HEAD. Example:</p>
<pre><code>import mechanize
class HeadRequest(mechanize.Request):
def get_method(self):
return "HEAD"
request = HeadRequest("http://www.example.com/")
response = mechanize.urlopen(request)
print response.info()
</code></pre>
| 8 | 2008-09-26T03:37:33Z | [
"python",
"http-headers",
"mechanize"
] |
How can I perform a HEAD request with the mechanize library? | 137,580 | <p>I know how to do a HEAD request with httplib, but I have to use mechanize for this site. </p>
<p>Essentially, what I need to do is grab a value from the header (filename) without actually downloading the file.</p>
<p>Any suggestions how I could accomplish this?</p>
| 3 | 2008-09-26T03:20:19Z | 12,680,334 | <p>In mechanize there is no need to do HeadRequest class etc.</p>
<p>Simply</p>
<pre><code>
import mechanize
br = mechanize.Browser()
r = br.open("http://www.example.com/")
print r.info()
</code></pre>
<p>That's all.</p>
| 0 | 2012-10-01T20:11:08Z | [
"python",
"http-headers",
"mechanize"
] |
Get Bound Event Handler in Tkinter | 138,029 | <p>After a bind a method to an event of a Tkinter element is there a way to get the method back?</p>
<pre><code>>>> root = Tkinter.Tk()
>>> frame = Tkinter.Frame(root, width=100, height=100)
>>> frame.bind('<Button-1>', lambda e: pprint('Click')) # function needed
>>> frame.pack()
>>> bound_event_method = frame.???
</code></pre>
| 1 | 2008-09-26T06:26:17Z | 138,039 | <p>Doesn't appear to be... why not just save it yourself if you're going to need it, or use a non-anonymous function?</p>
<p>Also, your code doesn't work as written: <code>lambda</code> functions can only contain expressions, not statements, so <code>print</code> is a no-go (this will change in Python 3.0 when <code>print()</code> becomes a function).</p>
| 0 | 2008-09-26T06:31:03Z | [
"python",
"user-interface",
"events",
"tkinter"
] |
Get Bound Event Handler in Tkinter | 138,029 | <p>After a bind a method to an event of a Tkinter element is there a way to get the method back?</p>
<pre><code>>>> root = Tkinter.Tk()
>>> frame = Tkinter.Frame(root, width=100, height=100)
>>> frame.bind('<Button-1>', lambda e: pprint('Click')) # function needed
>>> frame.pack()
>>> bound_event_method = frame.???
</code></pre>
| 1 | 2008-09-26T06:26:17Z | 138,258 | <p>The associated call to do that for the tk C API would be <a href="http://linux.about.com/library/cmd/blcmdl3_Tcl_GetCommandInfo.htm" rel="nofollow">Get_GetCommandInfo</a> which</p>
<blockquote>
<p>places information about the command
in the Tcl_CmdInfo structure pointed
to by infoPtr</p>
</blockquote>
<p>However this function is not used anywhere in <a href="http://svn.python.org/projects/python/trunk/Modules/_tkinter.c" rel="nofollow">_tkinter.c</a> which is the binding for tk used by python trough <a href="http://svn.python.org/projects/python/trunk/Lib/lib-tk/Tkinter.py" rel="nofollow">Tkinter.py</a>.</p>
<p>Therefore it is impossible to get the bound function out of tkinter. You need to remember that function yourself.</p>
| 2 | 2008-09-26T08:15:25Z | [
"python",
"user-interface",
"events",
"tkinter"
] |
Get Bound Event Handler in Tkinter | 138,029 | <p>After a bind a method to an event of a Tkinter element is there a way to get the method back?</p>
<pre><code>>>> root = Tkinter.Tk()
>>> frame = Tkinter.Frame(root, width=100, height=100)
>>> frame.bind('<Button-1>', lambda e: pprint('Click')) # function needed
>>> frame.pack()
>>> bound_event_method = frame.???
</code></pre>
| 1 | 2008-09-26T06:26:17Z | 226,141 | <p>The standard way to do this in Tcl/Tk is trivial: you use the same bind command but without the final argument. </p>
<pre><code>bind .b <Button-1> doSomething
puts "the function is [bind .b <Button-1>]"
=> the function is doSomething
</code></pre>
<p>You can do something similar with Tkinter but the results are, unfortunately, not quite as usable:</p>
<pre><code>e1.bind("<Button-1>",doSomething)
e1.bind("<Button-1>")
=> 'if {"[-1208974516doSomething %# %b %f %h %k %s %t %w %x %y %A %E %K %N %W %T %X %Y %D]" == "break"} break\n'
</code></pre>
<p>Obviously, Tkinter is doing a lot of juggling below the covers. One solution would be to write a little helper procedure that remembers this for you:</p>
<pre><code>def bindWidget(widget,event,func=None):
'''Set or retrieve the binding for an event on a widget'''
if not widget.__dict__.has_key("bindings"): widget.bindings=dict()
if func:
widget.bind(event,func)
widget.bindings[event] = func
else:
return(widget.bindings.setdefault(event,None))
</code></pre>
<p>You would use it like this:</p>
<pre><code>e1=Entry()
print "before, binding for <Button-1>: %s" % bindWidget(e1,"<Button-1>")
bindWidget(e1,"<Button-1>",doSomething)
print " after, binding for <Button-1>: %s" % bindWidget(e1,"<Button-1>")
</code></pre>
<p>When I run the above code I get:</p>
<pre><code>before, binding for <Button-1>: None
after, binding for <Button-1>: <function doSomething at 0xb7f2e79c>
</code></pre>
<p>As a final caveat, I don't use Tkinter much so I'm not sure what the ramifications are of dynamically adding an attribute to a widget instance. It seems to be harmless, but if not you can always create a global dictionary to keep track of the bindings.</p>
| 3 | 2008-10-22T15:01:35Z | [
"python",
"user-interface",
"events",
"tkinter"
] |
Is there something like Python's getattr() in C#? | 138,045 | <p>Is there something like <a href="http://effbot.org/zone/python-getattr.htm">Python's getattr()</a> in C#? I would like to create a window by reading a list which contains the names of controls to put on the window.</p>
| 12 | 2008-09-26T06:35:30Z | 138,053 | <p>Use reflection for this.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.type.getproperty.aspx" rel="nofollow"><code>Type.GetProperty()</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.type.getproperty.aspx" rel="nofollow"><code>Type.GetProperties()</code></a> each return <a href="http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx" rel="nofollow"><code>PropertyInfo</code></a> instances, which can be used to read a property value on an object.</p>
<pre><code>var result = typeof(DateTime).GetProperty("Year").GetValue(dt, null)
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/system.type.getmethod.aspx" rel="nofollow"><code>Type.GetMethod()</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.type.getmethods.aspx" rel="nofollow"><code>Type.GetMethods()</code></a> each return <a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.aspx" rel="nofollow"><code>MethodInfo</code></a> instances, which can be used to execute a method on an object.</p>
<pre><code>var result = typeof(DateTime).GetMethod("ToLongDateString").Invoke(dt, null);
</code></pre>
<p>If you don't necessarily know the type (which would be a little wierd if you new the property name), than you could do something like this as well.</p>
<pre><code>var result = dt.GetType().GetProperty("Year").Invoke(dt, null);
</code></pre>
| 3 | 2008-09-26T06:39:43Z | [
"c#",
"python",
"user-interface"
] |
Is there something like Python's getattr() in C#? | 138,045 | <p>Is there something like <a href="http://effbot.org/zone/python-getattr.htm">Python's getattr()</a> in C#? I would like to create a window by reading a list which contains the names of controls to put on the window.</p>
| 12 | 2008-09-26T06:35:30Z | 138,054 | <p>Yes, you can do this...</p>
<pre><code>typeof(YourObjectType).GetProperty("PropertyName").GetValue(instanceObjectToGetPropFrom, null);
</code></pre>
| 1 | 2008-09-26T06:40:58Z | [
"c#",
"python",
"user-interface"
] |
Is there something like Python's getattr() in C#? | 138,045 | <p>Is there something like <a href="http://effbot.org/zone/python-getattr.htm">Python's getattr()</a> in C#? I would like to create a window by reading a list which contains the names of controls to put on the window.</p>
| 12 | 2008-09-26T06:35:30Z | 138,063 | <p>There's the System.Reflection.PropertyInfo class that can be created using object.GetType().GetProperties(). That can be used to probe an object's properties using strings. (Similar methods exist for object methods, fields, etc.)</p>
<p>I don't think that will help you accomplish your goals though. You should probably just create and manipulate the objects directly. Controls have a Name property that you can set, for example.</p>
| 0 | 2008-09-26T06:46:51Z | [
"c#",
"python",
"user-interface"
] |
Is there something like Python's getattr() in C#? | 138,045 | <p>Is there something like <a href="http://effbot.org/zone/python-getattr.htm">Python's getattr()</a> in C#? I would like to create a window by reading a list which contains the names of controls to put on the window.</p>
| 12 | 2008-09-26T06:35:30Z | 138,079 | <p>There is also <a href="http://msdn.microsoft.com/en-us/library/66btctbe.aspx">Type.InvokeMember</a>.</p>
<pre><code>public static class ReflectionExt
{
public static object GetAttr(this object obj, string name)
{
Type type = obj.GetType();
BindingFlags flags = BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.GetProperty;
return type.InvokeMember(name, flags, Type.DefaultBinder, obj, null);
}
}
</code></pre>
<p>Which could be used like:</p>
<pre><code>object value = ReflectionExt.GetAttr(obj, "PropertyName");
</code></pre>
<p>or (as an extension method):</p>
<pre><code>object value = obj.GetAttr("PropertyName");
</code></pre>
| 9 | 2008-09-26T06:57:23Z | [
"c#",
"python",
"user-interface"
] |
How can I read the RGB value of a given pixel in Python? | 138,250 | <p>If I open an image with <code>open("image.jpg")</code>, how can I get the RGB values of a pixel, if I have the coordinates of the pixel?</p>
<p>Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?</p>
<p>It would be so much better if I didn't have to download any additional libraries.</p>
| 63 | 2008-09-26T08:10:50Z | 138,254 | <p>Image manipulation is a complex topic, and it's best if you <em>do</em> use a library. I can recommend <a href="http://newcenturycomputers.net/projects/gdmodule.html" rel="nofollow">gdmodule</a> which provides easy access to many different image formats from within Python.</p>
| 1 | 2008-09-26T08:14:23Z | [
"python",
"graphics",
"rgb"
] |
How can I read the RGB value of a given pixel in Python? | 138,250 | <p>If I open an image with <code>open("image.jpg")</code>, how can I get the RGB values of a pixel, if I have the coordinates of the pixel?</p>
<p>Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?</p>
<p>It would be so much better if I didn't have to download any additional libraries.</p>
| 63 | 2008-09-26T08:10:50Z | 138,260 | <p>It's probably best to use the <a href="http://www.pythonware.com/products/pil/">Python Image Library</a> to do this which I'm afraid is a separate download.</p>
<p>The easiest way to do what you want is via the <a href="http://effbot.org/imagingbook/image.htm">load() method on the Image object</a> which returns a pixel access object which you can manipulate like an array:</p>
<pre><code>from PIL import Image
im = Image.open("dead_parrot.jpg") #Can be many different formats.
pix = im.load()
print im.size #Get the width and hight of the image for iterating over
print pix[x,y] #Get the RGBA Value of the a pixel of an image
pix[x,y] = value # Set the RGBA Value of the image (tuple)
</code></pre>
<p>Alternatively, look at <a href="http://effbot.org/imagingbook/imagedraw.htm">ImageDraw</a> which gives a much richer API for creating images.</p>
| 108 | 2008-09-26T08:15:56Z | [
"python",
"graphics",
"rgb"
] |
How can I read the RGB value of a given pixel in Python? | 138,250 | <p>If I open an image with <code>open("image.jpg")</code>, how can I get the RGB values of a pixel, if I have the coordinates of the pixel?</p>
<p>Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?</p>
<p>It would be so much better if I didn't have to download any additional libraries.</p>
| 63 | 2008-09-26T08:10:50Z | 138,300 | <p>There's a really good article on wiki.wxpython.org entitled <a href="http://wiki.wxpython.org/index.cgi/WorkingWithImages" rel="nofollow">Working With Images</a>. The article mentions the possiblity of using wxWidgets (wxImage), PIL or PythonMagick. Personally, I've used PIL and wxWidgets and both make image manipulation fairly easy.</p>
| 3 | 2008-09-26T08:28:57Z | [
"python",
"graphics",
"rgb"
] |
How can I read the RGB value of a given pixel in Python? | 138,250 | <p>If I open an image with <code>open("image.jpg")</code>, how can I get the RGB values of a pixel, if I have the coordinates of the pixel?</p>
<p>Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?</p>
<p>It would be so much better if I didn't have to download any additional libraries.</p>
| 63 | 2008-09-26T08:10:50Z | 139,070 | <p><strong>PyPNG - lightweight PNG decoder/encoder</strong></p>
<p>Although the question hints at JPG, I hope my answer will be useful to some people.</p>
<p>Here's how to read and write PNG pixels using <a href="https://pypi.python.org/pypi/pypng/0.0.18" rel="nofollow">PyPNG module</a>:</p>
<pre><code>import png, array
point = (2, 10) # coordinates of pixel to be painted red
reader = png.Reader(filename='image.png')
w, h, pixels, metadata = reader.read_flat()
pixel_byte_width = 4 if metadata['alpha'] else 3
pixel_position = point[0] + point[1] * w
new_pixel_value = (255, 0, 0, 0) if metadata['alpha'] else (255, 0, 0)
pixels[
pixel_position * pixel_byte_width :
(pixel_position + 1) * pixel_byte_width] = array.array('B', new_pixel_value)
output = open('image-with-red-dot.png', 'wb')
writer = png.Writer(w, h, **metadata)
writer.write_array(output, pixels)
output.close()
</code></pre>
<p>PyPNG is a single pure Python module less than 4000 lines long, including tests and comments.</p>
<p><a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a> is a more comprehensive imaging library, but it's also significantly heavier.</p>
| 20 | 2008-09-26T12:20:38Z | [
"python",
"graphics",
"rgb"
] |
How can I read the RGB value of a given pixel in Python? | 138,250 | <p>If I open an image with <code>open("image.jpg")</code>, how can I get the RGB values of a pixel, if I have the coordinates of the pixel?</p>
<p>Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?</p>
<p>It would be so much better if I didn't have to download any additional libraries.</p>
| 63 | 2008-09-26T08:10:50Z | 663,861 | <p>You can use <a href="http://www.pygame.org" rel="nofollow">pygame</a>'s surfarray module. This module has a 3d pixel array returning method called pixels3d(surface). I've shown usage below:</p>
<pre><code>from pygame import surfarray, image, display
import pygame
import numpy #important to import
pygame.init()
image = image.load("myimagefile.jpg") #surface to render
resolution = (image.get_width(),image.get_height())
screen = display.set_mode(resolution) #create space for display
screen.blit(image, (0,0)) #superpose image on screen
display.flip()
surfarray.use_arraytype("numpy") #important!
screenpix = surfarray.pixels3d(image) #pixels in 3d array:
#[x][y][rgb]
for y in range(resolution[1]):
for x in range(resolution[0]):
for color in range(3):
screenpix[x][y][color] += 128
#reverting colors
screen.blit(surfarray.make_surface(screenpix), (0,0)) #superpose on screen
display.flip() #update display
while 1:
print finished
</code></pre>
<p>I hope been helpful. Last word: screen is locked for lifetime of screenpix.</p>
| 3 | 2009-03-19T20:14:21Z | [
"python",
"graphics",
"rgb"
] |
How can I read the RGB value of a given pixel in Python? | 138,250 | <p>If I open an image with <code>open("image.jpg")</code>, how can I get the RGB values of a pixel, if I have the coordinates of the pixel?</p>
<p>Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?</p>
<p>It would be so much better if I didn't have to download any additional libraries.</p>
| 63 | 2008-09-26T08:10:50Z | 5,365,853 | <p>As Dave Webb said.</p>
<p>Here is my working code snippet printing the pixel colours from an image:</p>
<pre><code>import os, sys
import Image
im = Image.open("image.jpg")
x = 3
y = 4
pix = im.load()
print pix[x,y]
</code></pre>
| 8 | 2011-03-20T00:10:43Z | [
"python",
"graphics",
"rgb"
] |
How can I read the RGB value of a given pixel in Python? | 138,250 | <p>If I open an image with <code>open("image.jpg")</code>, how can I get the RGB values of a pixel, if I have the coordinates of the pixel?</p>
<p>Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?</p>
<p>It would be so much better if I didn't have to download any additional libraries.</p>
| 63 | 2008-09-26T08:10:50Z | 22,877,878 | <p>install PIL using the command "sudo apt-get install python-imaging" and run the following program. It will print RGB values of the image. If the image is large redirect the output to a file using '>' later open the file to see RGB values</p>
<pre><code>import PIL
import Image
FILENAME='fn.gif' #image can be in gif jpeg or png format
im=Image.open(FILENAME).convert('RGB')
pix=im.load()
w=im.size[0]
h=im.size[1]
for i in range(w):
for j in range(h):
print pix[i,j]
</code></pre>
| 2 | 2014-04-05T07:23:04Z | [
"python",
"graphics",
"rgb"
] |
How can I read the RGB value of a given pixel in Python? | 138,250 | <p>If I open an image with <code>open("image.jpg")</code>, how can I get the RGB values of a pixel, if I have the coordinates of the pixel?</p>
<p>Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?</p>
<p>It would be so much better if I didn't have to download any additional libraries.</p>
| 63 | 2008-09-26T08:10:50Z | 27,370,477 | <p>You could use Tkinter module, which is already installed with Python.(I use Python 2.7 and OS X)</p>
<p>Here is the code from <a href="http://tkinter.unpythonic.net/wiki/PhotoImage" rel="nofollow">http://tkinter.unpythonic.net/wiki/PhotoImage</a>.</p>
<p>Set RGB values.</p>
<pre><code>from Tkinter import *
root = Tk()
def pixel(image, pos, color):
"""Place pixel at pos=(x,y) on image, with color=(r,g,b)."""
r,g,b = color
x,y = pos
image.put("#%02x%02x%02x" % (r,g,b), (y, x))
photo = PhotoImage(width=32, height=32)
pixel(photo, (16,16), (255,0,0)) # One lone pixel in the middle...
label = Label(root, image=photo)
label.grid()
root.mainloop()
</code></pre>
<p>And get RGB may like:</p>
<pre><code>#from http://www.kosbie.net/cmu/spring-14/15-112/handouts/steganographyEncoder.py
def getRGB(image, x, y):
value = image.get(x, y)
return tuple(map(int, value.split(" ")))
</code></pre>
| 1 | 2014-12-09T02:22:25Z | [
"python",
"graphics",
"rgb"
] |
How can I read the RGB value of a given pixel in Python? | 138,250 | <p>If I open an image with <code>open("image.jpg")</code>, how can I get the RGB values of a pixel, if I have the coordinates of the pixel?</p>
<p>Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?</p>
<p>It would be so much better if I didn't have to download any additional libraries.</p>
| 63 | 2008-09-26T08:10:50Z | 27,960,627 | <p>Using <a href="http://python-pillow.github.io/" rel="nofollow">Pillow</a> (which works with Python 3.X as well as Python 2.7+), you can do the following:</p>
<pre><code>from PIL import Image
im = Image.open('image.jpg', 'r')
width, height = im.size
pixel_values = list(im.getdata())
</code></pre>
<p>Now you have all pixel values. If it is RGB or another mode can be read by <code>im.mode</code>. Then you can get pixel <code>(x, y)</code> by:</p>
<pre><code>pixel_values[width*y+x]
</code></pre>
<p>Alternatively, you can use Numpy and reshape the array:</p>
<pre><code>>>> pixel_values = numpy.array(pixel_values).reshape((width, height, 3))
>>> x, y = 0, 1
>>> pixel_values[x][y]
[ 18 18 12]
</code></pre>
<p>A complete, simple to use solution is</p>
<pre><code>def get_image(image_path):
"""Get a numpy array of an image so that one can access values[x][y]."""
image = Image.open(image_path, 'r')
width, height = image.size
pixel_values = list(image.getdata())
if image.mode == 'RGB':
channels = 3
elif image.mode == 'L':
channels = 1
else:
print("Unknown mode: %s" % image.mode)
return None
pixel_values = numpy.array(pixel_values).reshape((width, height, channels))
return pixel_values
</code></pre>
| 4 | 2015-01-15T09:46:10Z | [
"python",
"graphics",
"rgb"
] |
How can I read the RGB value of a given pixel in Python? | 138,250 | <p>If I open an image with <code>open("image.jpg")</code>, how can I get the RGB values of a pixel, if I have the coordinates of the pixel?</p>
<p>Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?</p>
<p>It would be so much better if I didn't have to download any additional libraries.</p>
| 63 | 2008-09-26T08:10:50Z | 33,630,650 | <pre><code>photo = Image.open('IN.jpg') #your image
photo = photo.convert('RGB')
width = photo.size[0] #define W and H
height = photo.size[1]
for y in range(0, height): #each pixel has coordinates
row = ""
for x in range(0, width):
RGB = photo.getpixel((x,y))
R,G,B = RGB #now you can use the RGB value
</code></pre>
| 2 | 2015-11-10T13:02:32Z | [
"python",
"graphics",
"rgb"
] |
Dynamic radio button creation | 138,353 | <p>In wxPython, if I create a list of radio buttons and place the list initially, is it possible to change the contents in that list later?</p>
<p>For example, I have a panel that uses a boxSizer to place the widgets initially. One of those widgets is a list of radio buttons (I have also tried a normal radiobox). I would like to dynamically change the list based on variables from another class.</p>
<p>However, once the list is placed in the sizer, it's effectively "locked"; I can't just modify the list and have the changes appear. If I try re-adding the list to the sizer, it just gets put in the top left corner of the panel.</p>
<p>I'm sure I could hide the original list and manually place the new list in the same position but that feels like a kludge. I'm sure I'm making this harder than it is. I'm probably using the wrong widgets for this, much less the wrong approach, but I'm building this as a learning experience.</p>
<pre><code> class Job(wiz.WizardPageSimple):
"""Character's job class."""
def __init__(self, parent, title, attribs):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
self.charAttribs = attribs
#---Create widgets
self.Job_list = ["Aircraft Mechanic", "Vehicle Mechanic", "Electronics Specialist"]
box1_title = wx.StaticBox( self, -1, "" )
box1 = wx.StaticBoxSizer( box1_title, wx.VERTICAL )
grid1 = wx.BoxSizer(wx.VERTICAL)
for item in self.Job_list:
radio = wx.RadioButton(self, -1, item)
grid1.Add(radio)
##Debugging
self.btn = wx.Button(self, -1, "click")
self.Bind(wx.EVT_BUTTON, self.eligibleJob, self.btn)
#---Place widgets
self.sizer.Add(self.Job_intro)
self.sizer.Add(self.btn)
box1.Add(grid1)
self.sizer.Add(box1)
def eligibleJob(self, event):
"""Determine which Jobs a character is eligible for."""
if self.charAttribs.intelligence >= 12:
skillList = ["Analyst", "Interrogator", "Fire Specialist", "Aircraft Pilot"]
for skill in skillList:
self.Job_list.append(skill)
print self.Job_list ##Debugging
#return self.Job_list
</code></pre>
| 1 | 2008-09-26T08:54:37Z | 138,479 | <p>Two possible solutions</p>
<ol>
<li>Rebuild the sizer with the radio widgets each time you have to make a change</li>
<li>Hold the radio button widgets in a list, and call SetLabel each time you have to change their labels.</li>
</ol>
| 0 | 2008-09-26T09:34:03Z | [
"python",
"user-interface",
"layout",
"wxpython"
] |
Dynamic radio button creation | 138,353 | <p>In wxPython, if I create a list of radio buttons and place the list initially, is it possible to change the contents in that list later?</p>
<p>For example, I have a panel that uses a boxSizer to place the widgets initially. One of those widgets is a list of radio buttons (I have also tried a normal radiobox). I would like to dynamically change the list based on variables from another class.</p>
<p>However, once the list is placed in the sizer, it's effectively "locked"; I can't just modify the list and have the changes appear. If I try re-adding the list to the sizer, it just gets put in the top left corner of the panel.</p>
<p>I'm sure I could hide the original list and manually place the new list in the same position but that feels like a kludge. I'm sure I'm making this harder than it is. I'm probably using the wrong widgets for this, much less the wrong approach, but I'm building this as a learning experience.</p>
<pre><code> class Job(wiz.WizardPageSimple):
"""Character's job class."""
def __init__(self, parent, title, attribs):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
self.charAttribs = attribs
#---Create widgets
self.Job_list = ["Aircraft Mechanic", "Vehicle Mechanic", "Electronics Specialist"]
box1_title = wx.StaticBox( self, -1, "" )
box1 = wx.StaticBoxSizer( box1_title, wx.VERTICAL )
grid1 = wx.BoxSizer(wx.VERTICAL)
for item in self.Job_list:
radio = wx.RadioButton(self, -1, item)
grid1.Add(radio)
##Debugging
self.btn = wx.Button(self, -1, "click")
self.Bind(wx.EVT_BUTTON, self.eligibleJob, self.btn)
#---Place widgets
self.sizer.Add(self.Job_intro)
self.sizer.Add(self.btn)
box1.Add(grid1)
self.sizer.Add(box1)
def eligibleJob(self, event):
"""Determine which Jobs a character is eligible for."""
if self.charAttribs.intelligence >= 12:
skillList = ["Analyst", "Interrogator", "Fire Specialist", "Aircraft Pilot"]
for skill in skillList:
self.Job_list.append(skill)
print self.Job_list ##Debugging
#return self.Job_list
</code></pre>
| 1 | 2008-09-26T08:54:37Z | 139,009 | <p>To make new list elements appear in correct places, you have to re-layout the grid after adding new elements to it. For example, to add a few new items, you could call:</p>
<pre><code>def addNewSkills(self, newSkillList):
'''newSkillList is a list of skill names you want to add'''
for skillName in newSkillList:
newRadioButton = wx.RadioButton(self, -1, skillName)
self.grid1.Add(newRadioButton) # appears in top-left corner of the panel
self.Layout() # all newly added radio buttons appear where they should be
self.Fit() # if you need to resize the panel to fit new items, this will help
</code></pre>
<p>where <code>self.grid1</code> is the sizer you keep all your radio buttons on.</p>
| 1 | 2008-09-26T12:06:40Z | [
"python",
"user-interface",
"layout",
"wxpython"
] |
Dynamic radio button creation | 138,353 | <p>In wxPython, if I create a list of radio buttons and place the list initially, is it possible to change the contents in that list later?</p>
<p>For example, I have a panel that uses a boxSizer to place the widgets initially. One of those widgets is a list of radio buttons (I have also tried a normal radiobox). I would like to dynamically change the list based on variables from another class.</p>
<p>However, once the list is placed in the sizer, it's effectively "locked"; I can't just modify the list and have the changes appear. If I try re-adding the list to the sizer, it just gets put in the top left corner of the panel.</p>
<p>I'm sure I could hide the original list and manually place the new list in the same position but that feels like a kludge. I'm sure I'm making this harder than it is. I'm probably using the wrong widgets for this, much less the wrong approach, but I'm building this as a learning experience.</p>
<pre><code> class Job(wiz.WizardPageSimple):
"""Character's job class."""
def __init__(self, parent, title, attribs):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
self.charAttribs = attribs
#---Create widgets
self.Job_list = ["Aircraft Mechanic", "Vehicle Mechanic", "Electronics Specialist"]
box1_title = wx.StaticBox( self, -1, "" )
box1 = wx.StaticBoxSizer( box1_title, wx.VERTICAL )
grid1 = wx.BoxSizer(wx.VERTICAL)
for item in self.Job_list:
radio = wx.RadioButton(self, -1, item)
grid1.Add(radio)
##Debugging
self.btn = wx.Button(self, -1, "click")
self.Bind(wx.EVT_BUTTON, self.eligibleJob, self.btn)
#---Place widgets
self.sizer.Add(self.Job_intro)
self.sizer.Add(self.btn)
box1.Add(grid1)
self.sizer.Add(box1)
def eligibleJob(self, event):
"""Determine which Jobs a character is eligible for."""
if self.charAttribs.intelligence >= 12:
skillList = ["Analyst", "Interrogator", "Fire Specialist", "Aircraft Pilot"]
for skill in skillList:
self.Job_list.append(skill)
print self.Job_list ##Debugging
#return self.Job_list
</code></pre>
| 1 | 2008-09-26T08:54:37Z | 145,580 | <p>I was able to fix it by using the info DzinX provided, with some modification.</p>
<p>It appears that posting the radio buttons box first "locked in" the box to the sizer. If I tried to add a new box, I would get an error message stating that I was trying to add the widget to the same sizer twice.</p>
<p>By simply removing the radio buttons initially and having the user click a button to call a method, I could simply add a the list of radio buttons without a problem.</p>
<p>Additionally, by having the user click a button, I did not run into errors of "class Foo has no attribute 'bar'". Apparently, when the wizard initalizes, the attributes aren't available to the rest of the wizard pages. I had thought the wizard pages were dynamically created with each click of "Next" but they are all created at the same time.</p>
| 0 | 2008-09-28T09:47:15Z | [
"python",
"user-interface",
"layout",
"wxpython"
] |
Pure Python XSLT library | 138,502 | <p>Is there an XSLT library that is pure Python?</p>
<p>Installing libxml2+libxslt or any similar C libraries is a problem on some of the platforms I need to support.</p>
<p>I really only need basic XSLT support, and speed is not a major issue.</p>
| 19 | 2008-09-26T09:43:43Z | 138,545 | <p>Have you looked at <a href="http://4suite.org/index.xhtml" rel="nofollow">4suite</a>?</p>
| 1 | 2008-09-26T09:58:28Z | [
"python",
"xml",
"xslt"
] |
Pure Python XSLT library | 138,502 | <p>Is there an XSLT library that is pure Python?</p>
<p>Installing libxml2+libxslt or any similar C libraries is a problem on some of the platforms I need to support.</p>
<p>I really only need basic XSLT support, and speed is not a major issue.</p>
| 19 | 2008-09-26T09:43:43Z | 141,084 | <p>If you only need <em>basic</em> support, and your XML isn't too crazy, consider removing the XSLT element from the equation and just using a DOM/SAX parser.</p>
<p>Here's some info from the <a href="http://wiki.python.org/" rel="nofollow">PythonInfo Wiki</a>:</p>
<blockquote>
<p>[DOM] sucks up an entire XML file,
holds it in memory, and lets you work
with it. Sax, on the other hand, emits
events as it goes step by step through
the file.</p>
</blockquote>
<p>What do you think?</p>
| 1 | 2008-09-26T18:18:34Z | [
"python",
"xml",
"xslt"
] |
Pure Python XSLT library | 138,502 | <p>Is there an XSLT library that is pure Python?</p>
<p>Installing libxml2+libxslt or any similar C libraries is a problem on some of the platforms I need to support.</p>
<p>I really only need basic XSLT support, and speed is not a major issue.</p>
| 19 | 2008-09-26T09:43:43Z | 592,466 | <p>Unfortunately there are no pure-python XSLT processors at the moment. If you need something that is more platform independent, you may want to use a Java-based XSLT processor like <a href="http://saxon.sourceforge.net/">Saxon</a>. 4Suite is working on a pure-python XPath parser, but it doesn't look like a pure XSLT processor will be out for some time. Perhaps it would be best to use some of Python's functional capabilities to try and approximate the existing stylesheet or look into the feasibility of using Java instead.</p>
| 9 | 2009-02-26T21:13:59Z | [
"python",
"xml",
"xslt"
] |
Pure Python XSLT library | 138,502 | <p>Is there an XSLT library that is pure Python?</p>
<p>Installing libxml2+libxslt or any similar C libraries is a problem on some of the platforms I need to support.</p>
<p>I really only need basic XSLT support, and speed is not a major issue.</p>
| 19 | 2008-09-26T09:43:43Z | 1,832,692 | <p>I don't think you can do it in cpython: there are no pure python XSLT implementations.</p>
<p>But you can trivially do it in jython, using the inbuilt XSLT APIs of the JVM. I wrote a blog post for the specific case of doing it on Google AppEngine, but the code given should work under jython in anyn circumstances.</p>
<p>Transforming with XSLT on Google AppEngine and jython</p>
<p><a href="http://jython.xhaus.com/transforming-with-xslt-on-google-appengine-and-jython/">http://jython.xhaus.com/transforming-with-xslt-on-google-appengine-and-jython/</a></p>
<p>HTH,</p>
<p>Alan.</p>
| 6 | 2009-12-02T12:47:18Z | [
"python",
"xml",
"xslt"
] |
Pure Python XSLT library | 138,502 | <p>Is there an XSLT library that is pure Python?</p>
<p>Installing libxml2+libxslt or any similar C libraries is a problem on some of the platforms I need to support.</p>
<p>I really only need basic XSLT support, and speed is not a major issue.</p>
| 19 | 2008-09-26T09:43:43Z | 14,650,028 | <p>There's also <a href="http://lxml.de/" rel="nofollow">http://lxml.de/</a> </p>
<blockquote>
<p>"lxml is the most feature-rich and easy-to-use library for processing XML and HTML in the Python language."</p>
</blockquote>
| 1 | 2013-02-01T15:51:58Z | [
"python",
"xml",
"xslt"
] |
Is it feasible to compile Python to machine code? | 138,521 | <p>How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?</p>
<p>Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.</p>
<p>Also, you would need to bundle the Python interpreter if you wanted to do dynamic evaluation of expressions, but perhaps a subset of Python that didn't allow this would still be useful.</p>
<p>Would it provide any speed and/or memory usage advantages? Presumably the startup time of the Python interpreter would be eliminated (although shared libraries would still need loading at startup).</p>
| 93 | 2008-09-26T09:51:51Z | 138,539 | <p>This might seem reasonable at first glance, however there are a lot of ordinary things in Python that aren't directly mappable to to a C representation without carrying over a lot of the Python runtime support. For example, duck typing comes to mind. Many functions in Python that read input can take a file <em>or file-like</em> object, as long as it supports certain operations, eg. read() or readline(). If you think about what it would take to map this type of support to C, you begin to imagine exactly the sorts of things that the Python runtime system already does.</p>
<p>There are utilities such as <a href="http://www.py2exe.org/">py2exe</a> that will bundle a Python program and runtime into a single executable (as far as possible).</p>
| 6 | 2008-09-26T09:56:08Z | [
"python",
"c",
"linker",
"compilation"
] |
Is it feasible to compile Python to machine code? | 138,521 | <p>How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?</p>
<p>Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.</p>
<p>Also, you would need to bundle the Python interpreter if you wanted to do dynamic evaluation of expressions, but perhaps a subset of Python that didn't allow this would still be useful.</p>
<p>Would it provide any speed and/or memory usage advantages? Presumably the startup time of the Python interpreter would be eliminated (although shared libraries would still need loading at startup).</p>
| 93 | 2008-09-26T09:51:51Z | 138,548 | <p><a href="http://psyco.sourceforge.net/" rel="nofollow">Psyco</a> is a kind of just-in-time (JIT) compiler: dynamic compiler for Python, runs code 2-100 times faster, but it needs much memory.</p>
<p>In short: it run your existing Python software much faster, with no change in your source but it doesn't compile to object code the same way a C compiler would.</p>
| 2 | 2008-09-26T09:59:12Z | [
"python",
"c",
"linker",
"compilation"
] |
Is it feasible to compile Python to machine code? | 138,521 | <p>How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?</p>
<p>Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.</p>
<p>Also, you would need to bundle the Python interpreter if you wanted to do dynamic evaluation of expressions, but perhaps a subset of Python that didn't allow this would still be useful.</p>
<p>Would it provide any speed and/or memory usage advantages? Presumably the startup time of the Python interpreter would be eliminated (although shared libraries would still need loading at startup).</p>
| 93 | 2008-09-26T09:51:51Z | 138,553 | <p>Try <a href="http://shed-skin.blogspot.com/">ShedSkin</a> Python-to-C++ compiler, but it is far from perfect. Also there is Psyco - Python JIT if only speedup is needed. But IMHO this is not worth the effort. For speed-critical parts of code best solution would be to write them as C/C++ extensions. </p>
| 15 | 2008-09-26T10:00:15Z | [
"python",
"c",
"linker",
"compilation"
] |
Is it feasible to compile Python to machine code? | 138,521 | <p>How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?</p>
<p>Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.</p>
<p>Also, you would need to bundle the Python interpreter if you wanted to do dynamic evaluation of expressions, but perhaps a subset of Python that didn't allow this would still be useful.</p>
<p>Would it provide any speed and/or memory usage advantages? Presumably the startup time of the Python interpreter would be eliminated (although shared libraries would still need loading at startup).</p>
| 93 | 2008-09-26T09:51:51Z | 138,554 | <p>Jython has a compiler targeting JVM bytecode. The bytecode is fully dynamic, just like the Python language itself! Very cool. (Yes, as Greg Hewgill's answer alludes, the bytecode does use the Jython runtime, and so the Jython jar file must be distributed with your app.)</p>
| 2 | 2008-09-26T10:00:16Z | [
"python",
"c",
"linker",
"compilation"
] |
Is it feasible to compile Python to machine code? | 138,521 | <p>How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?</p>
<p>Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.</p>
<p>Also, you would need to bundle the Python interpreter if you wanted to do dynamic evaluation of expressions, but perhaps a subset of Python that didn't allow this would still be useful.</p>
<p>Would it provide any speed and/or memory usage advantages? Presumably the startup time of the Python interpreter would be eliminated (although shared libraries would still need loading at startup).</p>
| 93 | 2008-09-26T09:51:51Z | 138,582 | <p><a href="http://codespeak.net/pypy/dist/pypy/doc/home.html">PyPy</a> is a project to reimplement Python in Python, using compilation to native code as one of the implementation strategies (others being a VM with JIT, using JVM, etc.). Their compiled C versions run slower than CPython on average but much faster for some programs.</p>
<p><a href="http://code.google.com/p/shedskin/">Shedskin</a> is an experimental Python-to-C++ compiler.</p>
<p><a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/version/Doc/About.html">Pyrex</a> is a language specially designed for writing Python extension modules. It's designed to bridge the gap between the nice, high-level, easy-to-use world of Python and the messy, low-level world of C.</p>
| 11 | 2008-09-26T10:06:06Z | [
"python",
"c",
"linker",
"compilation"
] |
Is it feasible to compile Python to machine code? | 138,521 | <p>How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?</p>
<p>Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.</p>
<p>Also, you would need to bundle the Python interpreter if you wanted to do dynamic evaluation of expressions, but perhaps a subset of Python that didn't allow this would still be useful.</p>
<p>Would it provide any speed and/or memory usage advantages? Presumably the startup time of the Python interpreter would be eliminated (although shared libraries would still need loading at startup).</p>
| 93 | 2008-09-26T09:51:51Z | 138,585 | <p>As @Greg Hewgill says it, there are good reasons why this is not always possible. However, certain kinds of code (like very algorithmic code) can be turned into "real" machine code. </p>
<p>There are several options:</p>
<ul>
<li>Use <a href="http://psyco.sourceforge.net/">Psyco</a>, which emits machine code dynamically. You should choose carefully which methods/functions to convert, though.</li>
<li>Use <a href="http://cython.org/">Cython</a>, which is a Python-<em>like</em> language that is compiled into a Python C extension</li>
<li>Use <a href="http://pypy.org">PyPy</a>, which has a translator from RPython (a <em>restricted subset</em> of Python that does not support some of the most "dynamic" features of Python) to C or LLVM.
<ul>
<li>PyPy is still highly experimental</li>
<li>not all extensions will be present</li>
</ul></li>
</ul>
<p>After that, you can use one of the existing packages (freeze, Py2exe, PyInstaller) to put everything into one binary.</p>
<p>All in all: there is no general answer for your question. If you have Python code that is performance-critical, try to use as much builtin functionality as possible (or ask a "How do I make my Python code faster" question). If that doesn't help, try to identify the code and port it to C (or Cython) and use the extension.</p>
| 41 | 2008-09-26T10:06:43Z | [
"python",
"c",
"linker",
"compilation"
] |
Is it feasible to compile Python to machine code? | 138,521 | <p>How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?</p>
<p>Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.</p>
<p>Also, you would need to bundle the Python interpreter if you wanted to do dynamic evaluation of expressions, but perhaps a subset of Python that didn't allow this would still be useful.</p>
<p>Would it provide any speed and/or memory usage advantages? Presumably the startup time of the Python interpreter would be eliminated (although shared libraries would still need loading at startup).</p>
| 93 | 2008-09-26T09:51:51Z | 138,586 | <p><a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow">Pyrex</a> is a subset of the Python language that compiles to C, done by the guy that first built <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">list comprehensions</a> for Python. It was mainly developed for building wrappers but can be used in a more general context. <a href="http://cython.org/" rel="nofollow">Cython</a> is a more actively maintained fork of pyrex.</p>
| 8 | 2008-09-26T10:06:46Z | [
"python",
"c",
"linker",
"compilation"
] |
Is it feasible to compile Python to machine code? | 138,521 | <p>How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?</p>
<p>Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.</p>
<p>Also, you would need to bundle the Python interpreter if you wanted to do dynamic evaluation of expressions, but perhaps a subset of Python that didn't allow this would still be useful.</p>
<p>Would it provide any speed and/or memory usage advantages? Presumably the startup time of the Python interpreter would be eliminated (although shared libraries would still need loading at startup).</p>
| 93 | 2008-09-26T09:51:51Z | 138,605 | <p>The answer is "Yes, it is possible". You could take Python code and attempt to compile it into the equivalent C code using the CPython API. In fact, there used to be a Python2C project that did just that, but I haven't heard about it in many years (back in the Python 1.5 days is when I last saw it.)</p>
<p>You could attempt to translate the Python code into native C as much as possible, and fall back to the CPython API when you need actual Python features. I've been toying with that idea myself the last month or two. It is, however, an awful lot of work, and an enormous amount of Python features are very hard to translate into C: nested functions, generators, anything but simple classes with simple methods, anything involving modifying module globals from outside the module, etc, etc.</p>
| 2 | 2008-09-26T10:14:09Z | [
"python",
"c",
"linker",
"compilation"
] |
Is it feasible to compile Python to machine code? | 138,521 | <p>How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?</p>
<p>Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.</p>
<p>Also, you would need to bundle the Python interpreter if you wanted to do dynamic evaluation of expressions, but perhaps a subset of Python that didn't allow this would still be useful.</p>
<p>Would it provide any speed and/or memory usage advantages? Presumably the startup time of the Python interpreter would be eliminated (although shared libraries would still need loading at startup).</p>
| 93 | 2008-09-26T09:51:51Z | 11,415,005 | <p>py2c ( <a href="http://code.google.com/p/py2c">http://code.google.com/p/py2c</a>) can convert python code to c/c++
I am the solo developer of py2c.</p>
| 14 | 2012-07-10T14:00:44Z | [
"python",
"c",
"linker",
"compilation"
] |
Is it feasible to compile Python to machine code? | 138,521 | <p>How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?</p>
<p>Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.</p>
<p>Also, you would need to bundle the Python interpreter if you wanted to do dynamic evaluation of expressions, but perhaps a subset of Python that didn't allow this would still be useful.</p>
<p>Would it provide any speed and/or memory usage advantages? Presumably the startup time of the Python interpreter would be eliminated (although shared libraries would still need loading at startup).</p>
| 93 | 2008-09-26T09:51:51Z | 22,952,452 | <p><a href="http://www.nuitka.net/">Nuitka</a> is a Python to C++ compiler that links against libpython. It appears to be a relatively new project. The author claims a <a href="http://www.nuitka.net/pages/overview.html">speed improvement</a> over CPython on the pystone benchmark. </p>
| 6 | 2014-04-09T03:52:37Z | [
"python",
"c",
"linker",
"compilation"
] |
Is it feasible to compile Python to machine code? | 138,521 | <p>How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?</p>
<p>Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.</p>
<p>Also, you would need to bundle the Python interpreter if you wanted to do dynamic evaluation of expressions, but perhaps a subset of Python that didn't allow this would still be useful.</p>
<p>Would it provide any speed and/or memory usage advantages? Presumably the startup time of the Python interpreter would be eliminated (although shared libraries would still need loading at startup).</p>
| 93 | 2008-09-26T09:51:51Z | 23,596,973 | <p>This doesn't compile Python to machine code. But allows to create a shared library to call Python code.</p>
<p>If what you are looking for is an easy way to run Python code from C without relying on execp stuff. You could generate a shared library from python code wrapped with a few calls to <a href="https://docs.python.org/2.7/c-api/intro.html#embedding-python" rel="nofollow">Python embedding API</a>. Well the application is a shared library, an .so that you can use in many other libraries/applications.</p>
<p>Here is a simple example which create a shared library, that you can link with a C program. The shared library executes Python code.</p>
<p>The python file that will be executed is <code>pythoncalledfromc.py</code>:</p>
<pre><code># -*- encoding:utf-8 -*-
# this file must be named "pythoncalledfrom.py"
def main(string): # args must a string
print "python is called from c"
print "string sent by «c» code is:"
print string
print "end of «c» code input"
return 0xc0c4 # return something
</code></pre>
<p>You can try it with <code>python2 -c "import pythoncalledfromc; pythoncalledfromc.main('HELLO')</code>. It will output:</p>
<pre><code>python is called from c
string sent by «c» code is:
HELLO
end of «c» code input
</code></pre>
<p>The shared library will be defined by the following by <code>callpython.h</code>:</p>
<pre><code>#ifndef CALL_PYTHON
#define CALL_PYTHON
void callpython_init(void);
int callpython(char ** arguments);
void callpython_finalize(void);
#endif
</code></pre>
<p>The associated <code>callpython.c</code> is:</p>
<pre><code>// gcc `python2.7-config --ldflags` `python2.7-config --cflags` callpython.c -lpython2.7 -shared -fPIC -o callpython.so
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <python2.7/Python.h>
#include "callpython.h"
#define PYTHON_EXEC_STRING_LENGTH 52
#define PYTHON_EXEC_STRING "import pythoncalledfromc; pythoncalledfromc.main(\"%s\")"
void callpython_init(void) {
Py_Initialize();
}
int callpython(char ** arguments) {
int arguments_string_size = (int) strlen(*arguments);
char * python_script_to_execute = malloc(arguments_string_size + PYTHON_EXEC_STRING_LENGTH);
PyObject *__main__, *locals;
PyObject * result = NULL;
if (python_script_to_execute == NULL)
return -1;
__main__ = PyImport_AddModule("__main__");
if (__main__ == NULL)
return -1;
locals = PyModule_GetDict(__main__);
sprintf(python_script_to_execute, PYTHON_EXEC_STRING, *arguments);
result = PyRun_String(python_script_to_execute, Py_file_input, locals, locals);
if(result == NULL)
return -1;
return 0;
}
void callpython_finalize(void) {
Py_Finalize();
}
</code></pre>
<p>You can compile it with the following command:</p>
<pre><code>gcc `python2.7-config --ldflags` `python2.7-config --cflags` callpython.c -lpython2.7 -shared -fPIC -o callpython.so
</code></pre>
<p>Create a file named <code>callpythonfromc.c</code> that contains the following:</p>
<pre><code>#include "callpython.h"
int main(void) {
char * example = "HELLO";
callpython_init();
callpython(&example);
callpython_finalize();
return 0;
}
</code></pre>
<p>Compile it and run:</p>
<pre><code>gcc callpythonfromc.c callpython.so -o callpythonfromc
PYTHONPATH=`pwd` LD_LIBRARY_PATH=`pwd` ./callpythonfromc
</code></pre>
<p>This is a very basic example. It can work, but depending on the library it might be still difficult to serialize C data structures to Python and from Python to C. Things can be automated somewhat...</p>
<p><a href="http://stackoverflow.com/questions/138521/is-it-feasible-to-compile-python-to-machine-code/23596973#23596973">Nuitka</a> might be helpful.</p>
<p>Also there is <a href="http://numba.pydata.org/" rel="nofollow">numba</a> but they both don't aim to do what you want exactly. Generating a C header from Python code is possible, but only if you specify the how to convert the Python types to C types or can infer that information. See <a href="https://bitbucket.org/logilab/astroid" rel="nofollow">python astroid</a> for a Python ast analyzer.</p>
| 2 | 2014-05-11T19:29:38Z | [
"python",
"c",
"linker",
"compilation"
] |
Is it feasible to compile Python to machine code? | 138,521 | <p>How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?</p>
<p>Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.</p>
<p>Also, you would need to bundle the Python interpreter if you wanted to do dynamic evaluation of expressions, but perhaps a subset of Python that didn't allow this would still be useful.</p>
<p>Would it provide any speed and/or memory usage advantages? Presumably the startup time of the Python interpreter would be eliminated (although shared libraries would still need loading at startup).</p>
| 93 | 2008-09-26T09:51:51Z | 32,293,870 | <p>Some extra references:</p>
<ul>
<li><p><a href="https://github.com/dropbox/pyston" rel="nofollow">https://github.com/dropbox/pyston</a> is a JIT compiler for Python developped by Dropbox</p></li>
<li><p><a href="http://pythonhosted.org/pythran" rel="nofollow">http://pythonhosted.org/pythran</a> is a compile-time python to C++ translator for scientific computing</p></li>
<li><p><a href="https://github.com/cosmo-ethz/hope" rel="nofollow">https://github.com/cosmo-ethz/hope</a> is a JIT python to C++ translator for scientific computing</p></li>
</ul>
| 3 | 2015-08-30T06:27:35Z | [
"python",
"c",
"linker",
"compilation"
] |
Can Regex be used for this particular string manipulation? | 138,552 | <p>I need to replace character (say) <strong>x</strong> with character (say) <strong>P</strong> in a string, but only if it is contained in a quoted substring.
An example makes it clearer:</p>
<pre><code>axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k
</code></pre>
<p>Let's assume, for the sake of simplicity, that quotes always come in pairs. </p>
<p>The obvious way is to just process the string one character at a time (a simple state machine approach);<br />
however, I'm wondering if regular expressions can be used to do all the processing in one go.</p>
<p>My target language is C#, but I guess my question pertains to any language having builtin or library support for regular expressions.</p>
| 7 | 2008-09-26T10:00:10Z | 138,594 | <p>Not with plain regexp. Regular expressions have no "memory" so they cannot distinguish between being "inside" or "outside" quotes. </p>
<p>You need something more powerful, for example using <a href="http://gema.sourceforge.net" rel="nofollow">gema</a> it would be straighforward:</p>
<pre><code>'<repl>'=$0
repl:x=P
</code></pre>
| 1 | 2008-09-26T10:08:42Z | [
"c#",
"python",
"regex",
"language-agnostic"
] |
Can Regex be used for this particular string manipulation? | 138,552 | <p>I need to replace character (say) <strong>x</strong> with character (say) <strong>P</strong> in a string, but only if it is contained in a quoted substring.
An example makes it clearer:</p>
<pre><code>axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k
</code></pre>
<p>Let's assume, for the sake of simplicity, that quotes always come in pairs. </p>
<p>The obvious way is to just process the string one character at a time (a simple state machine approach);<br />
however, I'm wondering if regular expressions can be used to do all the processing in one go.</p>
<p>My target language is C#, but I guess my question pertains to any language having builtin or library support for regular expressions.</p>
| 7 | 2008-09-26T10:00:10Z | 138,598 | <p>Sorry to break your hopes, but you need a push-down automata to do that. There is more info here:
<a href="http://en.wikipedia.org/wiki/Pushdown_automaton" rel="nofollow">Pushdown Automaton</a></p>
<p>In short, Regular expressions, which are finite state machines can only read and has no memory while pushdown automaton has a stack and manipulating capabilities.</p>
<p>Edit: spelling...</p>
| 0 | 2008-09-26T10:10:00Z | [
"c#",
"python",
"regex",
"language-agnostic"
] |
Can Regex be used for this particular string manipulation? | 138,552 | <p>I need to replace character (say) <strong>x</strong> with character (say) <strong>P</strong> in a string, but only if it is contained in a quoted substring.
An example makes it clearer:</p>
<pre><code>axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k
</code></pre>
<p>Let's assume, for the sake of simplicity, that quotes always come in pairs. </p>
<p>The obvious way is to just process the string one character at a time (a simple state machine approach);<br />
however, I'm wondering if regular expressions can be used to do all the processing in one go.</p>
<p>My target language is C#, but I guess my question pertains to any language having builtin or library support for regular expressions.</p>
| 7 | 2008-09-26T10:00:10Z | 138,615 | <p>I was able to do this with Python:</p>
<pre><code>>>> import re
>>> re.sub(r"x(?=[^']*'([^']|'[^']*')*$)", "P", "axbx'cxdxe'fxgh'ixj'k")
"axbx'cPdPe'fxgh'iPj'k"
</code></pre>
<p>What this does is use the non-capturing match (?=...) to check that the character x is within a quoted string. It looks for some nonquote characters up to the next quote, then looks for a sequence of either single characters or quoted groups of characters, until the end of the string.</p>
<p>This relies on your assumption that the quotes are always balanced. This is also not very efficient.</p>
| 8 | 2008-09-26T10:18:50Z | [
"c#",
"python",
"regex",
"language-agnostic"
] |
Can Regex be used for this particular string manipulation? | 138,552 | <p>I need to replace character (say) <strong>x</strong> with character (say) <strong>P</strong> in a string, but only if it is contained in a quoted substring.
An example makes it clearer:</p>
<pre><code>axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k
</code></pre>
<p>Let's assume, for the sake of simplicity, that quotes always come in pairs. </p>
<p>The obvious way is to just process the string one character at a time (a simple state machine approach);<br />
however, I'm wondering if regular expressions can be used to do all the processing in one go.</p>
<p>My target language is C#, but I guess my question pertains to any language having builtin or library support for regular expressions.</p>
| 7 | 2008-09-26T10:00:10Z | 138,620 | <p>Similar discussion about balanced text replaces: <a href="http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns#133771">http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns#133771</a></p>
<p>Although you can try this in Vim, but it works well only if the string is on one line, and there's only one pair of 's.</p>
<pre><code>:%s:\('[^']*\)x\([^']*'\):\1P\2:gci
</code></pre>
<p>If there's one more pair or even an unbalanced ', then it could fail. That's way I included the <code>c</code> a.k.a. confirm flag on the <code>ex</code> command.</p>
<p>The same can be done with sed, without the interaction - or with <code>awk</code> so you can add some interaction.</p>
<p>One possible solution is to break the lines on pairs of <code>'</code>s then you can do with vim solution. </p>
| 1 | 2008-09-26T10:19:31Z | [
"c#",
"python",
"regex",
"language-agnostic"
] |
Can Regex be used for this particular string manipulation? | 138,552 | <p>I need to replace character (say) <strong>x</strong> with character (say) <strong>P</strong> in a string, but only if it is contained in a quoted substring.
An example makes it clearer:</p>
<pre><code>axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k
</code></pre>
<p>Let's assume, for the sake of simplicity, that quotes always come in pairs. </p>
<p>The obvious way is to just process the string one character at a time (a simple state machine approach);<br />
however, I'm wondering if regular expressions can be used to do all the processing in one go.</p>
<p>My target language is C#, but I guess my question pertains to any language having builtin or library support for regular expressions.</p>
| 7 | 2008-09-26T10:00:10Z | 138,755 | <p>I converted Greg Hewgill's python code to C# and it worked!</p>
<pre><code>[Test]
public void ReplaceTextInQuotes()
{
Assert.AreEqual("axbx'cPdPe'fxgh'iPj'k",
Regex.Replace("axbx'cxdxe'fxgh'ixj'k",
@"x(?=[^']*'([^']|'[^']*')*$)", "P"));
}
</code></pre>
<p>That test passed.</p>
| 9 | 2008-09-26T11:04:02Z | [
"c#",
"python",
"regex",
"language-agnostic"
] |
Can Regex be used for this particular string manipulation? | 138,552 | <p>I need to replace character (say) <strong>x</strong> with character (say) <strong>P</strong> in a string, but only if it is contained in a quoted substring.
An example makes it clearer:</p>
<pre><code>axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k
</code></pre>
<p>Let's assume, for the sake of simplicity, that quotes always come in pairs. </p>
<p>The obvious way is to just process the string one character at a time (a simple state machine approach);<br />
however, I'm wondering if regular expressions can be used to do all the processing in one go.</p>
<p>My target language is C#, but I guess my question pertains to any language having builtin or library support for regular expressions.</p>
| 7 | 2008-09-26T10:00:10Z | 139,467 | <pre><code>Pattern: (?s)\G((?:^[^']*'|(?<=.))(?:'[^']*'|[^'x]+)*+)x
Replacement: \1P
</code></pre>
<ol>
<li><code>\G</code> — Anchor each match at the end of the previous one, or the start of the string.</li>
<li><code>(?:^[^']*'|(?<=.))</code> — If it is at the beginning of the string, match up to the first quote.</li>
<li><code>(?:'[^']*'|[^'x]+)*+</code> — Match any block of unquoted characters, or any (non-quote) characters up to an 'x'.</li>
</ol>
<p>One sweep trough the source string, except for a single character look-behind.</p>
| 1 | 2008-09-26T13:22:18Z | [
"c#",
"python",
"regex",
"language-agnostic"
] |
Can Regex be used for this particular string manipulation? | 138,552 | <p>I need to replace character (say) <strong>x</strong> with character (say) <strong>P</strong> in a string, but only if it is contained in a quoted substring.
An example makes it clearer:</p>
<pre><code>axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k
</code></pre>
<p>Let's assume, for the sake of simplicity, that quotes always come in pairs. </p>
<p>The obvious way is to just process the string one character at a time (a simple state machine approach);<br />
however, I'm wondering if regular expressions can be used to do all the processing in one go.</p>
<p>My target language is C#, but I guess my question pertains to any language having builtin or library support for regular expressions.</p>
| 7 | 2008-09-26T10:00:10Z | 139,802 | <p>The trick is to use non-capturing group to match the part of the string <em>following</em> the match (character <strong>x</strong>) we are searching for.
Trying to match the string up to <strong>x</strong> will only find either the first or the last occurence, depending whether non-greedy quantifiers are used.
Here's Greg's idea transposed to Tcl, with comments.</p>
<pre>
set strIn {axbx'cxdxe'fxgh'ixj'k}
set regex {(?x) # enable expanded syntax
# - allows comments, ignores whitespace
x # the actual match
(?= # non-matching group
[^']*' # match to end of current quoted substring
##
## assuming quotes are in pairs,
## make sure we actually were
## inside a quoted substring
## by making sure the rest of the string
## is what we expect it to be
##
(
[^']* # match any non-quoted substring
| # ...or...
'[^']*' # any quoted substring, including the quotes
)* # any number of times
$ # until we run out of string :)
) # end of non-matching group
}
#the same regular expression without the comments
set regexCondensed {(?x)x(?=[^']*'([^']|'[^']*')*$)}
set replRegex {P}
set nMatches [regsub -all -- $regex $strIn $replRegex strOut]
puts "$nMatches replacements. "
if {$nMatches > 0} {
puts "Original: |$strIn|"
puts "Result: |$strOut|"
}
exit
</pre>
<p>This prints:</p>
<pre><code>3 replacements.
Original: |axbx'cxdxe'fxgh'ixj'k|
Result: |axbx'cPdPe'fxgh'iPj'k|
</code></pre>
| 2 | 2008-09-26T14:17:33Z | [
"c#",
"python",
"regex",
"language-agnostic"
] |
Can Regex be used for this particular string manipulation? | 138,552 | <p>I need to replace character (say) <strong>x</strong> with character (say) <strong>P</strong> in a string, but only if it is contained in a quoted substring.
An example makes it clearer:</p>
<pre><code>axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k
</code></pre>
<p>Let's assume, for the sake of simplicity, that quotes always come in pairs. </p>
<p>The obvious way is to just process the string one character at a time (a simple state machine approach);<br />
however, I'm wondering if regular expressions can be used to do all the processing in one go.</p>
<p>My target language is C#, but I guess my question pertains to any language having builtin or library support for regular expressions.</p>
| 7 | 2008-09-26T10:00:10Z | 140,977 | <pre><code>#!/usr/bin/perl -w
use strict;
# Break up the string.
# The spliting uses quotes
# as the delimiter.
# Put every broken substring
# into the @fields array.
my @fields;
while (<>) {
@fields = split /'/, $_;
}
# For every substring indexed with an odd
# number, search for x and replace it
# with P.
my $count;
my $end = $#fields;
for ($count=0; $count < $end; $count++) {
if ($count % 2 == 1) {
$fields[$count] =~ s/a/P/g;
}
}
</code></pre>
<p>Wouldn't this chunk do the job?</p>
| 2 | 2008-09-26T17:56:13Z | [
"c#",
"python",
"regex",
"language-agnostic"
] |
Can Regex be used for this particular string manipulation? | 138,552 | <p>I need to replace character (say) <strong>x</strong> with character (say) <strong>P</strong> in a string, but only if it is contained in a quoted substring.
An example makes it clearer:</p>
<pre><code>axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k
</code></pre>
<p>Let's assume, for the sake of simplicity, that quotes always come in pairs. </p>
<p>The obvious way is to just process the string one character at a time (a simple state machine approach);<br />
however, I'm wondering if regular expressions can be used to do all the processing in one go.</p>
<p>My target language is C#, but I guess my question pertains to any language having builtin or library support for regular expressions.</p>
| 7 | 2008-09-26T10:00:10Z | 150,711 | <p>A more general (and simpler) solution which allows non-paired quotes.</p>
<ol>
<li>Find quoted string</li>
<li><p>Replace 'x' by 'P' in the string</p>
<pre><code>#!/usr/bin/env python
import re
text = "axbx'cxdxe'fxgh'ixj'k"
s = re.sub("'.*?'", lambda m: re.sub("x", "P", m.group(0)), text)
print s == "axbx'cPdPe'fxgh'iPj'k", s
# -> True axbx'cPdPe'fxgh'iPj'k
</code></pre></li>
</ol>
| 2 | 2008-09-29T21:16:12Z | [
"c#",
"python",
"regex",
"language-agnostic"
] |
Vim extension (via Python)? | 138,680 | <p>is it possible to extend vim functionality via custom extension (preferably, written in Python)?</p>
<p>What I need ideally is custom command when in command mode. E.g.</p>
<p>ESC</p>
<p>:do_this</p>
<p>:do_that</p>
| 10 | 2008-09-26T10:45:57Z | 138,709 | <p>vim supports scripting in python (and in perl as well, I think).</p>
<p>You just have to make sure that the vim distribution you are using has been compiled with python support.</p>
<p>If you are using a Linux system, you can download the source and then compile it with</p>
<pre><code>./configure --enable-pythoninterp
make
sudo make install
</code></pre>
<p>Inside vim, you can type</p>
<pre><code>:version
</code></pre>
<p>to list the available features; if it has python support, you should see a '+python' somewhere (a '-python' otherwise).</p>
<p>Then, to check the usage of the python module, you can type</p>
<pre><code>:help python
</code></pre>
<p>P.S: if you're going to compile the vim sources, make sure to check the available configure options, you might need to specify --with-python-config-dir as well.</p>
<p>P.P.S: to create a "custom command in command mode" (if I understand correctly what you mean), you can create a function "MyFunction" in a vim script (using python or the vim scripting language) and then invoke it with </p>
<pre><code>:Call MyFunction()
</code></pre>
<p>Check </p>
<pre><code>:help user-functions
</code></pre>
<p>for details</p>
| 19 | 2008-09-26T10:55:13Z | [
"python",
"vim"
] |
Vim extension (via Python)? | 138,680 | <p>is it possible to extend vim functionality via custom extension (preferably, written in Python)?</p>
<p>What I need ideally is custom command when in command mode. E.g.</p>
<p>ESC</p>
<p>:do_this</p>
<p>:do_that</p>
| 10 | 2008-09-26T10:45:57Z | 138,720 | <p>Yes it is. There are several extensions on <a href="http://www.vim.org/scripts/index.php" rel="nofollow">http://www.vim.org/scripts/index.php</a> </p>
<p>It can be done with python as well if the support for python is compiled in. </p>
<p>Article about it: <a href="http://www.techrepublic.com/article/extending-vim-with-python/" rel="nofollow">http://www.techrepublic.com/article/extending-vim-with-python/</a> </p>
<p>Google is our friend.</p>
<p>HTH</p>
| 5 | 2008-09-26T10:57:54Z | [
"python",
"vim"
] |
Vim extension (via Python)? | 138,680 | <p>is it possible to extend vim functionality via custom extension (preferably, written in Python)?</p>
<p>What I need ideally is custom command when in command mode. E.g.</p>
<p>ESC</p>
<p>:do_this</p>
<p>:do_that</p>
| 10 | 2008-09-26T10:45:57Z | 5,293,536 | <p>Had a problems to compile Vim with Python. </p>
<p>"...checking if compile and link flags for Python are sane... no: PYTHON DISABLED" in the ./configure output.</p>
<p>On Ubuntu 10.04 you have to install '<strong>python2.6-dev</strong>'. The flags for ./configure are:</p>
<p>--enable-pythoninterp</p>
<p>--with-python-config-dir=/usr/lib/python2.6/<strong>config</strong></p>
<p>Make sure you got a path to directory, which contains '<strong>config.c</strong>' file. Also no '<strong>/</strong>' at the end of the path! That caused me problems.</p>
| 3 | 2011-03-14T00:29:53Z | [
"python",
"vim"
] |
How do I test a django database schema? | 138,851 | <p>I want to write tests that can show whether or not the database is in sync with my models.py file. Actually I have already written them, only to find out that django creates a new database each time the tests are run based on the models.py file.
Is there any way I can make the <strong>models.py test</strong> use the existing database schema? The one that's in mysql/postgresql, and not the one that's in /myapp/models.py ?</p>
<p>I don't care about the data that's in the database, I only care about it's <strong>schema</strong> i.e. I want my tests to notice if a table in the database has less fields than the schema in my models.py file. </p>
<p>I'm using the unittest framework (actually the django extension to it) if this has any relevance.</p>
<p>thanks</p>
| 6 | 2008-09-26T11:23:51Z | 139,137 | <p>What we did was override the default test_runner so that it wouldn't create a new database to test against. This way, it runs the test against whatever our current local database looks like. But be very careful if you use this method because any changes to data you make in your tests will be permanent. I made sure that all our tests restores any changes back to their original state, and keep our pristine version of our database on the server and backed up.</p>
<p>So to do this you need to copy the run_test method from django.test.simple to a location in your project -- I put mine in myproject/test/test_runner.py</p>
<p>Then make the following changes to that method:</p>
<pre><code>// change
old_name = settings.DATABASE_NAME
from django.db import connection
connection.creation.create_test_db(verbosity, autoclobber=not interactive)
result = unittest.TextTestRunner(verbosity=verbosity).run(suite)
connection.creation.destroy_test_db(old_name, verbosity)
// to:
result = unittest.TextTestRunner(verbosity=verbosity).run(suite)
</code></pre>
<p>Make sure to do all the necessary imports at the top and then in your settings file set the setting:</p>
<pre><code>TEST_RUNNER = 'myproject.test.test_runner.run_tests'
</code></pre>
<p>Now when you run ./manage.py test Django will run the tests against the current state of your database rather than creating a new version based on your current model definitions.</p>
<p>Another thing you can do is create a copy of your database locally, and then do a check in your new run_test() method like this:</p>
<pre><code>if settings.DATABASE_NAME != 'my_test_db':
sys.exit("You cannot run tests using the %s database. Please switch DATABASE_NAME to my_test_db in settings.py" % settings.DATABASE_NAME)
</code></pre>
<p>That way there's no danger of running tests against your main database.</p>
| 8 | 2008-09-26T12:32:46Z | [
"python",
"django",
"unit-testing",
"model"
] |
PyQt - QScrollBar | 139,005 | <p>Dear Stacktoverflow, can you show me an example of how to use a QScrollBar? Thanks.</p>
| 0 | 2008-09-26T12:05:29Z | 139,056 | <p>It will come down to you using the QScrollArea, it is a widget that implements showing something that is larger than the available space. You will not need to use QScrollBar directly. I don't have a PyQt example but there is a C++ example in the QT distribution it is called the "Image Viewer". The object hierarchy will still be the same </p>
| 1 | 2008-09-26T12:18:12Z | [
"python",
"pyqt"
] |
PyQt - QScrollBar | 139,005 | <p>Dear Stacktoverflow, can you show me an example of how to use a QScrollBar? Thanks.</p>
| 0 | 2008-09-26T12:05:29Z | 139,082 | <p>In the PyQT source code distribution, look at the file:</p>
<blockquote>
<p>examples/widgets/sliders.pyw</p>
</blockquote>
<p>Or there is a minimal example <a href="http://www.zetcode.com/tutorials/pyqt4/widgets/" rel="nofollow">here</a> (I guess I shouldn't copy paste because of potential copyright issues)</p>
| 0 | 2008-09-26T12:23:54Z | [
"python",
"pyqt"
] |
PyQt - QScrollBar | 139,005 | <p>Dear Stacktoverflow, can you show me an example of how to use a QScrollBar? Thanks.</p>
| 0 | 2008-09-26T12:05:29Z | 139,107 | <pre><code>>>> import sys
>>> from PyQt4 import QtCore, QtGui
>>> app = QtGui.QApplication(sys.argv)
>>> sb = QtGui.QScrollBar()
>>> sb.setMinimum(0)
>>> sb.setMaximum(100)
>>> def on_slider_moved(value): print "new slider position: %i" % (value, )
>>> sb.connect(sb, QtCore.SIGNAL("sliderMoved(int)"), on_slider_moved)
>>> sb.show()
>>> app.exec_()
</code></pre>
<p>Now, when you move the slider (you might have to resize the window), you'll see the slider position printed to the terminal as you the handle.</p>
| 2 | 2008-09-26T12:28:38Z | [
"python",
"pyqt"
] |
listing all functions in a python module | 139,180 | <p>I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. </p>
<p>I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?</p>
<p>eg. something like:</p>
<pre><code>from somemodule import foo
print foo.methods # or whatever is the correct method to call
</code></pre>
| 164 | 2008-09-26T12:38:52Z | 139,193 | <p>You can use <code>dir(module)</code> to see all available methods/attributes. Also check out PyDocs.</p>
| 238 | 2008-09-26T12:40:20Z | [
"python"
] |
listing all functions in a python module | 139,180 | <p>I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. </p>
<p>I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?</p>
<p>eg. something like:</p>
<pre><code>from somemodule import foo
print foo.methods # or whatever is the correct method to call
</code></pre>
| 164 | 2008-09-26T12:38:52Z | 139,198 | <p>The inspect module. Also see the <a href="http://docs.python.org/2/library/pydoc.html"><code>pydoc</code></a> module, the <code>help()</code> function in the interactive interpreter and the <code>pydoc</code> command-line tool which generates the documentation you are after. You can just give them the class you wish to see the documentation of. They can also generate, for instance, HTML output and write it to disk.</p>
| 69 | 2008-09-26T12:41:04Z | [
"python"
] |
listing all functions in a python module | 139,180 | <p>I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. </p>
<p>I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?</p>
<p>eg. something like:</p>
<pre><code>from somemodule import foo
print foo.methods # or whatever is the correct method to call
</code></pre>
| 164 | 2008-09-26T12:38:52Z | 139,258 | <pre><code>import types
import yourmodule
print [yourmodule.__dict__.get(a) for a in dir(yourmodule)
if isinstance(yourmodule.__dict__.get(a), types.FunctionType)]
</code></pre>
| 44 | 2008-09-26T12:50:39Z | [
"python"
] |
listing all functions in a python module | 139,180 | <p>I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. </p>
<p>I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?</p>
<p>eg. something like:</p>
<pre><code>from somemodule import foo
print foo.methods # or whatever is the correct method to call
</code></pre>
| 164 | 2008-09-26T12:38:52Z | 140,106 | <p>Once you've <code>import</code>ed the module, you can just do:</p>
<pre><code> help(modulename)
</code></pre>
<p>... To get the docs on all the functions at once, interactively. Or you can use:</p>
<pre><code> dir(modulename)
</code></pre>
<p>... To simply list the names of all the functions and variables defined in the module.</p>
| 76 | 2008-09-26T15:08:54Z | [
"python"
] |
listing all functions in a python module | 139,180 | <p>I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. </p>
<p>I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?</p>
<p>eg. something like:</p>
<pre><code>from somemodule import foo
print foo.methods # or whatever is the correct method to call
</code></pre>
| 164 | 2008-09-26T12:38:52Z | 142,501 | <p>This will do the trick:</p>
<pre><code>dir(module)
</code></pre>
<p>However, if you find it annoying to read the returned list, just use the following loop to get one name per line.</p>
<pre><code>for i in dir(module): print i
</code></pre>
| 20 | 2008-09-26T23:41:16Z | [
"python"
] |
listing all functions in a python module | 139,180 | <p>I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. </p>
<p>I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?</p>
<p>eg. something like:</p>
<pre><code>from somemodule import foo
print foo.methods # or whatever is the correct method to call
</code></pre>
| 164 | 2008-09-26T12:38:52Z | 9,794,849 | <p>An example with inspect:</p>
<pre><code>from inspect import getmembers, isfunction
from my_project import my_module
functions_list = [o for o in getmembers(my_module) if isfunction(o[1])]
</code></pre>
<p>getmembers returns a list of (object_name, object_type) tuples.</p>
<p>You can replace isfunction with any of the other isXXX functions in the inspect module.</p>
| 37 | 2012-03-20T20:59:57Z | [
"python"
] |
listing all functions in a python module | 139,180 | <p>I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. </p>
<p>I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?</p>
<p>eg. something like:</p>
<pre><code>from somemodule import foo
print foo.methods # or whatever is the correct method to call
</code></pre>
| 164 | 2008-09-26T12:38:52Z | 10,079,706 | <p><code>dir(module)</code> is the standard way when using a script or the standard interpreter, as mentioned in most answers.</p>
<p>However with an interactive python shell like <a href="http://ipython.org">IPython</a> you can use tab-completion to get an overview of all objects defined in the module.
This is much more convenient, than using a script and <code>print</code> to see what is defined in the module.</p>
<ul>
<li><code>module.<tab></code> will show you all objects defined in the module (functions, classes and so on)</li>
<li><code>module.ClassX.<tab></code> will show you the methods and attributes of a class</li>
<li><code>module.function_xy?</code> or <code>module.ClassX.method_xy?</code> will show you the docstring of that function / method</li>
<li><code>module.function_x??</code> or <code>module.SomeClass.method_xy??</code> will show you the source code of the function / method. </li>
</ul>
| 13 | 2012-04-09T20:51:58Z | [
"python"
] |
listing all functions in a python module | 139,180 | <p>I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. </p>
<p>I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?</p>
<p>eg. something like:</p>
<pre><code>from somemodule import foo
print foo.methods # or whatever is the correct method to call
</code></pre>
| 164 | 2008-09-26T12:38:52Z | 11,173,131 | <p>It is not (or at least no longer) proper to use dir(module). The code should read like this:</p>
<pre><code>dir('module') or dir('modules')
</code></pre>
<p>Or you specify the module you want like this: <code>dir('sys')</code> to produce results from the module name sys. <code>dir()</code> returns errors while <code>dir('')</code> is what you need. *help('') will return help information if available for most functions. eg; <code>help('modules')</code> will return module help info.</p>
<p>Thanks for all the down votes. I was using Python3.2.2 and other 3x versions when I posted this. The point was to use (' stuff ') instead of the previous ( stuff ). But I'm assuming your all stuck on Python2 or using newer versions for PC not mobile like I was. </p>
<p><a href="http://effbot.org/librarybook/sys.htm" rel="nofollow">http://effbot.org/librarybook/sys.htm</a></p>
| -5 | 2012-06-23T21:29:31Z | [
"python"
] |
listing all functions in a python module | 139,180 | <p>I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. </p>
<p>I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?</p>
<p>eg. something like:</p>
<pre><code>from somemodule import foo
print foo.methods # or whatever is the correct method to call
</code></pre>
| 164 | 2008-09-26T12:38:52Z | 30,584,102 | <p>None of these answers will work if you are unable to import said Python file without import errors. This was the case for me when I was inspecting a file which comes from a large code base with a lot of dependencies. The following will process the file as text and search for all method names that start with "def" and print them and their line numbers.</p>
<pre><code>import re
pattern = re.compile("def (.*)\(")
for i, line in enumerate(open('Example.py')):
for match in re.finditer(pattern, line):
print '%s: %s' % (i+1, match.groups()[0])
</code></pre>
| 0 | 2015-06-01T22:05:25Z | [
"python"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.