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 |
---|---|---|---|---|---|---|---|---|---|
Most efficient way to search the last x lines of a file in python | 260,273 | <p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p>
<pre><code>s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 29 | 2008-11-03T23:01:50Z | 260,287 | <p>You could read chunks of 1,000 bytes or so from the end of the file into a buffer until you have 10 lines.</p>
| 1 | 2008-11-03T23:06:54Z | [
"python",
"file",
"search"
] |
Most efficient way to search the last x lines of a file in python | 260,273 | <p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p>
<pre><code>s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 29 | 2008-11-03T23:01:50Z | 260,312 | <p>I think reading the last 2 KB or so of the file should make sure you get 10 lines, and shouldn't be too much of a resource hog.</p>
<pre><code>file_handle = open("somefile")
file_size = file_handle.tell()
file_handle.seek(max(file_size - 2*1024, 0))
# this will get rid of trailing newlines, unlike readlines()
last_10 = file_handle.read().splitlines()[-10:]
assert len(last_10) == 10, "Only read %d lines" % len(last_10)
</code></pre>
| 7 | 2008-11-03T23:21:29Z | [
"python",
"file",
"search"
] |
Most efficient way to search the last x lines of a file in python | 260,273 | <p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p>
<pre><code>s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 29 | 2008-11-03T23:01:50Z | 260,324 | <p>Personally I'd be tempted to break out to the shell and call tail -n10 to load the file. But then I'm not really a Python programmer ;)</p>
| 0 | 2008-11-03T23:27:11Z | [
"python",
"file",
"search"
] |
Most efficient way to search the last x lines of a file in python | 260,273 | <p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p>
<pre><code>s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 29 | 2008-11-03T23:01:50Z | 260,339 | <p>I think I remember adapting the code from <a href="http://manugarg.blogspot.com/2007/04/tailing-in-python.html" rel="nofollow">this blog post from Manu Garg</a> when I had to do something similar.</p>
| 2 | 2008-11-03T23:35:00Z | [
"python",
"file",
"search"
] |
Most efficient way to search the last x lines of a file in python | 260,273 | <p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p>
<pre><code>s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 29 | 2008-11-03T23:01:50Z | 260,352 | <pre><code># Tail
from __future__ import with_statement
find_str = "FIREFOX" # String to find
fname = "g:/autoIt/ActiveWin.log_2" # File to check
with open(fname, "r") as f:
f.seek (0, 2) # Seek @ EOF
fsize = f.tell() # Get Size
f.seek (max (fsize-1024, 0), 0) # Set pos @ last n chars
lines = f.readlines() # Read to end
lines = lines[-10:] # Get last 10 lines
# This returns True if any line is exactly find_str + "\n"
print find_str + "\n" in lines
# If you're searching for a substring
for line in lines:
if find_str in line:
print True
break
</code></pre>
| 27 | 2008-11-03T23:40:34Z | [
"python",
"file",
"search"
] |
Most efficient way to search the last x lines of a file in python | 260,273 | <p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p>
<pre><code>s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 29 | 2008-11-03T23:01:50Z | 260,359 | <p>First, a function that returns a list:</p>
<pre><code>def lastNLines(file, N=10, chunksize=1024):
lines = None
file.seek(0,2) # go to eof
size = file.tell()
for pos in xrange(chunksize,size-1,chunksize):
# read a chunk
file.seek(pos,2)
chunk = file.read(chunksize)
if lines is None:
# first time
lines = chunk.splitlines()
else:
# other times, update the 'first' line with
# the new data, and re-split
lines[0:1] = (chunk + lines[0]).splitlines()
if len(lines) > N:
return lines[-N:]
file.seek(0)
chunk = file.read(size-pos)
lines[0:1] = (chunk + lines[0]).splitlines()
return lines[-N:]
</code></pre>
<p>Second, a function that iterates over the lines in reverse order:</p>
<pre><code>def iter_lines_reversed(file, chunksize=1024):
file.seek(0,2)
size = file.tell()
last_line = ""
for pos in xrange(chunksize,size-1,chunksize):
# read a chunk
file.seek(pos,2)
chunk = file.read(chunksize) + last_line
# split into lines
lines = chunk.splitlines()
last_line = lines[0]
# iterate in reverse order
for index,line in enumerate(reversed(lines)):
if index > 0:
yield line
# handle the remaining data at the beginning of the file
file.seek(0)
chunk = file.read(size-pos) + last_line
lines = chunk.splitlines()
for line in reversed(lines):
yield line
</code></pre>
<p>For your example:</p>
<pre><code>s = "foo"
for index, line in enumerate(iter_lines_reversed(fileObj)):
if line == s:
print "FOUND"
break
elif index+1 >= 10:
break
</code></pre>
<p><strong>Edit:</strong> Now gets the file-size automaticly<br />
<strong>Edit2:</strong> Now only iterates for 10 lines.</p>
| 0 | 2008-11-03T23:43:06Z | [
"python",
"file",
"search"
] |
Most efficient way to search the last x lines of a file in python | 260,273 | <p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p>
<pre><code>s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 29 | 2008-11-03T23:01:50Z | 260,394 | <p>If you are running Python on a POSIX system, you can use 'tail -10' to retrieve the last few lines. This may be faster than writing your own Python code to get the last 10 lines. Rather than opening the file directly, open a pipe from the command 'tail -10 filename'. If you are certain of the log output though (for example, you know that there are <strong>never</strong> any very long lines that are hundreds or thousands of characters long) then using one of the 'read the last 2KB' approaches listed would be fine.</p>
| 8 | 2008-11-04T00:04:13Z | [
"python",
"file",
"search"
] |
Most efficient way to search the last x lines of a file in python | 260,273 | <p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p>
<pre><code>s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 29 | 2008-11-03T23:01:50Z | 260,407 | <p>If you're on a unix box, <code>os.popen("tail -10 " + filepath).readlines()</code> will probably be the fastest way. Otherwise, it depends on how robust you want it to be. The methods proposed so far will all fall down, one way or another. For robustness and speed in the most common case you probably want something like a logarithmic search: use file.seek to go to end of the file minus 1000 characters, read it in, check how many lines it contains, then to EOF minus 3000 characters, read in 2000 characters, count the lines, then EOF minus 7000, read in 4000 characters, count the lines, etc. until you have as many lines as you need. But if you know for sure that it's always going to be run on files with sensible line lengths, you may not need that.</p>
<p>You might also find some inspiration in the <a href="http://www.koders.com/c/fid8DEE98A42C35A1346FA89C328CC3BF94E25CF377.aspx" rel="nofollow">source code</a> for the unix <code>tail</code> command.</p>
| 1 | 2008-11-04T00:08:58Z | [
"python",
"file",
"search"
] |
Most efficient way to search the last x lines of a file in python | 260,273 | <p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p>
<pre><code>s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 29 | 2008-11-03T23:01:50Z | 260,433 | <p>Here's an answer like MizardX's, but without its apparent problem of taking quadratic time in the worst case from rescanning the working string repeatedly for newlines as chunks are added.</p>
<p>Compared to the activestate solution (which also seems to be quadratic), this doesn't blow up given an empty file, and does one seek per block read instead of two.</p>
<p>Compared to spawning 'tail', this is self-contained. (But 'tail' is best if you have it.)</p>
<p>Compared to grabbing a few kB off the end and hoping it's enough, this works for any line length.</p>
<pre><code>import os
def reversed_lines(file):
"Generate the lines of file in reverse order."
part = ''
for block in reversed_blocks(file):
for c in reversed(block):
if c == '\n' and part:
yield part[::-1]
part = ''
part += c
if part: yield part[::-1]
def reversed_blocks(file, blocksize=4096):
"Generate blocks of file's contents in reverse order."
file.seek(0, os.SEEK_END)
here = file.tell()
while 0 < here:
delta = min(blocksize, here)
here -= delta
file.seek(here, os.SEEK_SET)
yield file.read(delta)
</code></pre>
<p>To use it as requested:</p>
<pre><code>from itertools import islice
def check_last_10_lines(file, key):
for line in islice(reversed_lines(file), 10):
if line.rstrip('\n') == key:
print 'FOUND'
break
</code></pre>
<p><strong>Edit:</strong> changed map() to itertools.imap() in head(). <strong>Edit 2:</strong> simplified reversed_blocks(). <strong>Edit 3:</strong> avoid rescanning tail for newlines. <strong>Edit 4:</strong> rewrote reversed_lines() because str.splitlines() ignores a final '\n', as BrianB noticed (thanks).</p>
<p>Note that in very old Python versions the string concatenation in a loop here will take quadratic time. CPython from at least the last few years avoids this problem automatically.</p>
| 29 | 2008-11-04T00:19:26Z | [
"python",
"file",
"search"
] |
Most efficient way to search the last x lines of a file in python | 260,273 | <p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p>
<pre><code>s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 29 | 2008-11-03T23:01:50Z | 260,648 | <p>I ran into that problem, parsing the last hour of LARGE syslog files, and used this function from activestate's recipe site... (<a href="http://code.activestate.com/recipes/439045/" rel="nofollow">http://code.activestate.com/recipes/439045/</a>)</p>
<pre><code>!/usr/bin/env python
# -*-mode: python; coding: iso-8859-1 -*-
#
# Copyright (c) Peter Astrand <[email protected]>
import os
import string
class BackwardsReader:
"""Read a file line by line, backwards"""
BLKSIZE = 4096
def readline(self):
while 1:
newline_pos = string.rfind(self.buf, "\n")
pos = self.file.tell()
if newline_pos != -1:
# Found a newline
line = self.buf[newline_pos+1:]
self.buf = self.buf[:newline_pos]
if pos != 0 or newline_pos != 0 or self.trailing_newline:
line += "\n"
return line
else:
if pos == 0:
# Start-of-file
return ""
else:
# Need to fill buffer
toread = min(self.BLKSIZE, pos)
self.file.seek(-toread, 1)
self.buf = self.file.read(toread) + self.buf
self.file.seek(-toread, 1)
if pos - toread == 0:
self.buf = "\n" + self.buf
def __init__(self, file):
self.file = file
self.buf = ""
self.file.seek(-1, 2)
self.trailing_newline = 0
lastchar = self.file.read(1)
if lastchar == "\n":
self.trailing_newline = 1
self.file.seek(-1, 2)
# Example usage
br = BackwardsReader(open('bar'))
while 1:
line = br.readline()
if not line:
break
print repr(line)
</code></pre>
<p>It works really well and is much more efficient then anything like fileObj.readlines()[-10:], which makes python read the entire file into memory and then chops the last ten lines off of it.</p>
| 2 | 2008-11-04T02:37:04Z | [
"python",
"file",
"search"
] |
Most efficient way to search the last x lines of a file in python | 260,273 | <p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p>
<pre><code>s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 29 | 2008-11-03T23:01:50Z | 260,973 | <p>Here is a version using <code>mmap</code> that seems pretty efficient. The big plus is that <code>mmap</code> will automatically handle the file to memory paging requirements for you.</p>
<pre><code>import os
from mmap import mmap
def lastn(filename, n):
# open the file and mmap it
f = open(filename, 'r+')
m = mmap(f.fileno(), os.path.getsize(f.name))
nlcount = 0
i = m.size() - 1
if m[i] == '\n': n += 1
while nlcount < n and i > 0:
if m[i] == '\n': nlcount += 1
i -= 1
if i > 0: i += 2
return m[i:].splitlines()
target = "target string"
print [l for l in lastn('somefile', 10) if l == target]
</code></pre>
| 5 | 2008-11-04T05:21:41Z | [
"python",
"file",
"search"
] |
Most efficient way to search the last x lines of a file in python | 260,273 | <p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p>
<pre><code>s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 29 | 2008-11-03T23:01:50Z | 262,921 | <p>This solution will read the file only once, but using 2 file object pointers to be able obtain the last N lines of file without re-reading it:</p>
<pre><code>def getLastLines (path, n):
# return the las N lines from the file indicated in path
fp = open(path)
for i in range(n):
line = fp.readline()
if line == '':
return []
back = open(path)
for each in fp:
back.readline()
result = []
for line in back:
result.append(line[:-1])
return result
s = "foo"
last_bit = getLastLines(r'C:\Documents and Settings\ricardo.m.reyes\My Documents\desarrollo\tail.py', 10)
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 0 | 2008-11-04T18:50:40Z | [
"python",
"file",
"search"
] |
Most efficient way to search the last x lines of a file in python | 260,273 | <p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p>
<pre><code>s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 29 | 2008-11-03T23:01:50Z | 262,988 | <p>You could also count the lines as you reverse through the file, instead of guessing at a byte offset. </p>
<pre><code>lines = 0
chunk_size = 1024
f = file('filename')
f.seek(0, 2)
f.seek(f.tell() - chunk_size)
while True:
s = f.read(chunk_size)
lines += s.count('\n')
if lines > NUM_OF_LINES:
break
f.seek(f.tell() - chunk_size*2)
</code></pre>
<p>Now the file is at a good position to run <code>readlines()</code>. You also could cache the strings you read the first time, to eliminate reading the same portion of the file twice.</p>
| 1 | 2008-11-04T19:03:35Z | [
"python",
"file",
"search"
] |
Most efficient way to search the last x lines of a file in python | 260,273 | <p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p>
<pre><code>s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 29 | 2008-11-03T23:01:50Z | 2,436,554 | <p>Maybe this might be useful:</p>
<pre><code>import os.path
path = 'path_to_file'
os.system('tail -n1 ' + path)
</code></pre>
| 0 | 2010-03-12T23:30:58Z | [
"python",
"file",
"search"
] |
Most efficient way to search the last x lines of a file in python | 260,273 | <p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p>
<pre><code>s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
</code></pre>
| 29 | 2008-11-03T23:01:50Z | 17,841,165 | <p>I took mhawke's suggestion to use <code>mmap</code> and wrote a version that uses <code>rfind</code>:</p>
<pre><code>from mmap import mmap
import sys
def reverse_file(f):
mm = mmap(f.fileno(), 0)
nl = mm.size() - 1
prev_nl = mm.size()
while nl > -1:
nl = mm.rfind('\n', 0, nl)
yield mm[nl + 1:prev_nl]
prev_nl = nl + 1
def main():
# Example usage
with open('test.txt', 'r+') as infile:
for line in reverse_file(infile):
sys.stdout.write(line)
</code></pre>
| 1 | 2013-07-24T17:43:52Z | [
"python",
"file",
"search"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 260,770 | <p>You can find information about Python audio here: <a href="http://wiki.python.org/moin/Audio/">http://wiki.python.org/moin/Audio/</a></p>
<p>It doesn't look like it can play .mp3 files without external libraries. You could either convert your .mp3 file to a .wav or other format, or use a library like <a href="http://pymedia.org/">PyMedia</a>.</p>
| 11 | 2008-11-04T03:27:13Z | [
"python",
"audio"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 260,901 | <p>Your best bet is probably to use <a href="http://www.pygame.org" rel="nofollow">pygame/SDL</a>. It's an external library, but it has great support across platforms.</p>
<pre><code>pygame.mixer.init()
pygame.mixer.music.load("file.mp3")
pygame.mixer.music.play()
</code></pre>
<p>You can find more specific documentation about the audio mixer support in the <a href="http://www.pygame.org/docs/ref/music.html" rel="nofollow">pygame.mixer.music documentation</a></p>
| 19 | 2008-11-04T04:40:50Z | [
"python",
"audio"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 260,924 | <p>You can't do this without a nonstandard library.</p>
<p>for windows users who end up in this thread, try <a href="http://python.net/crew/mhammond/win32/" rel="nofollow">pythonwin</a>. <a href="http://www.pygame.org/docs/ref/mixer.html" rel="nofollow">PyGame</a> has some sound support. For hardware accelerated game audio, you'll probably need to call OpenAL or similar through ctypes.</p>
| 1 | 2008-11-04T04:52:24Z | [
"python",
"audio"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 262,084 | <p><a href="http://pyglet.org/">Pyglet</a> has the ability to play back audio through an external library called <a href="http://code.google.com/p/avbin">AVbin</a>. Pyglet is a ctypes wrapper around native system calls on each platform it supports. Unfortunately, I don't think anything in the standard library will play audio back.</p>
| 5 | 2008-11-04T14:37:24Z | [
"python",
"audio"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 507,464 | <p>If you need portable Python audio library try <a href="http://people.csail.mit.edu/hubert/pyaudio/">PyAudio</a>. It certainly has a mac port.</p>
<p>As for mp3 files: it's certainly doable in "raw" Python, only I'm afraid you'd have to code everything yourself :). If you can afford some external library I've found some <a href="http://n2.nabble.com/Lame-python-bindings-td33898.html">PyAudio - PyLame sample</a> here.</p>
| 6 | 2009-02-03T15:08:52Z | [
"python",
"audio"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 14,018,627 | <p>You can see this: <a href="http://www.speech.kth.se/snack/" rel="nofollow">http://www.speech.kth.se/snack/</a></p>
<pre><code>s = Sound()
s.read('sound.wav')
s.play()
</code></pre>
| 4 | 2012-12-24T07:48:54Z | [
"python",
"audio"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 20,746,883 | <p>In <a href="http://pydub.com" rel="nofollow">pydub</a> we've recently <a href="https://github.com/jiaaro/pydub/blob/master/pydub/playback.py" rel="nofollow">opted to use ffplay (via subprocess)</a> from the ffmpeg suite of tools, which internally uses SDL.</p>
<p>It works for our purposes â mainly just making it easier to test the results of pydub code in interactive mode â but it has it's downsides, like causing a new program to appear in the dock on mac.</p>
<p>I've linked the implementation above, but a simplified version follows:</p>
<pre><code>import subprocess
def play(audio_file_path):
subprocess.call(["ffplay", "-nodisp", "-autoexit", audio_file_path])
</code></pre>
<p>The <code>-nodisp</code> flag stops ffplay from showing a new window, and the <code>-autoexit</code> flag causes ffplay to exit and return a status code when the audio file is done playing.</p>
<p><strong>edit</strong>: pydub now uses pyaudio for playback when it's installed and falls back to ffplay to avoid the downsides I mentioned. The link above shows that implementation as well.</p>
| 8 | 2013-12-23T15:54:08Z | [
"python",
"audio"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 22,689,253 | <p>If you're on OSX, you can use the "os" module or "subprocess" etc. to call the OSX "play" command. From the OSX shell, it looks like </p>
<p>play "bah.wav"</p>
<p>It starts to play in about a half-second on my machine.</p>
| 0 | 2014-03-27T13:33:35Z | [
"python",
"audio"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 28,248,604 | <p>Also on OSX - from <a href="http://stackoverflow.com/questions/3498313/how-to-trigger-from-python-playing-of-a-wav-or-mp3-audio-file-on-a-mac">SO</a>, using OSX's <a href="https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/afplay.1.html" rel="nofollow">afplay</a> command:</p>
<pre><code>import subprocess
subprocess.call(["afplay", "path/to/audio/file"])
</code></pre>
| 2 | 2015-01-31T05:45:03Z | [
"python",
"audio"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 30,141,027 | <p>VLC has some nice python bindings here, for me this worked better than pyglet, at least on Mac OS:</p>
<p><a href="https://wiki.videolan.org/Python_bindings" rel="nofollow">https://wiki.videolan.org/Python_bindings</a></p>
<p>But it does rely on the VLC application, unfortunately</p>
| 1 | 2015-05-09T14:22:11Z | [
"python",
"audio"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 34,179,010 | <p>Sorry for the late reply, but I think this is a good place to advertise my library ...</p>
<p>AFAIK, the standard library has only one module for playing audio: <a href="https://docs.python.org/3/library/ossaudiodev.html" rel="nofollow">ossaudiodev</a>.
Sadly, this only works on Linux and FreeBSD.</p>
<p>UPDATE: There is also <a href="https://docs.python.org/3/library/winsound.html" rel="nofollow">winsound</a>, but obviously this is also platform-specific.</p>
<p>For something more platform-independent, you'll need to use an external library.</p>
<p>My recommendation is the <a href="http://python-sounddevice.rtfd.org/" rel="nofollow">sounddevice</a> module (but beware, I'm the author).</p>
<p>The package includes the pre-compiled <a href="http://www.portaudio.com/" rel="nofollow">PortAudio</a> library for Mac OS X and Windows, and can be easily installed with:</p>
<pre><code>pip install soundfile --user
</code></pre>
<p>It can play back sound from NumPy arrays, but it can also use plain Python buffers (if NumPy is not available).</p>
<p>To play back a NumPy array, that's all you need (assuming that the audio data has a sampling frequency of 44100 Hz):</p>
<pre><code>import sounddevice as sd
sd.play(myarray, 44100)
</code></pre>
<p>For more details, have a look at the <a href="http://python-sounddevice.rtfd.org/" rel="nofollow">documentation</a>.</p>
<p>It cannot read/write sound files, you'll need a separate library for that.</p>
| 3 | 2015-12-09T12:37:18Z | [
"python",
"audio"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 34,568,298 | <p>It is possible to play audio in OS X without any 3rd party libraries using an analogue of the following code. The raw audio data can be input with wave_wave.writeframes. This code extracts 4 seconds of audio from the input file.</p>
<pre><code>import wave
import io
from AppKit import NSSound
wave_output = io.BytesIO()
wave_shell = wave.open(wave_output, mode="wb")
file_path = 'SINE.WAV'
input_audio = wave.open(file_path)
input_audio_frames = input_audio.readframes(input_audio.getnframes())
wave_shell.setnchannels(input_audio.getnchannels())
wave_shell.setsampwidth(input_audio.getsampwidth())
wave_shell.setframerate(input_audio.getframerate())
seconds_multiplier = input_audio.getnchannels() * input_audio.getsampwidth() * input_audio.getframerate()
wave_shell.writeframes(input_audio_frames[second_multiplier:second_multiplier*5])
wave_shell.close()
wave_output.seek(0)
wave_data = wave_output.read()
audio_stream = NSSound.alloc()
audio_stream.initWithData_(wave_data)
audio_stream.play()
</code></pre>
| 1 | 2016-01-02T16:53:43Z | [
"python",
"audio"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 34,984,200 | <p><a href="http://stackoverflow.com/a/34568298/901641">Aaron's answer</a> appears to be about 10x more complicated than necessary. Just do this if you only need an answer that works on OS X:</p>
<pre><code>from AppKit import NSSound
sound = NSSound.alloc()
sound.initWithContentsOfFile_byReference_('/path/to/file.wav', True)
sound.play()
</code></pre>
<p>One thing... this returns immediately. So you might want to also do this, if you want the call to block until the sound finishes playing.</p>
<pre><code>from time import sleep
sleep(sound.duration())
</code></pre>
<p>Edit: I took this function and combined it with variants for Windows and Linux. The result is a pure python, cross platform module with no dependencies called <a href="https://pypi.python.org/pypi/playsound" rel="nofollow">playsound</a>. I've uploaded it to pypi.</p>
<pre><code>pip install playsound
</code></pre>
<p>Then run it like this:</p>
<pre><code>from playsound import playsound
playsound('/path/to/file.wav', block = False)
</code></pre>
<p>MP3 files also work on OS X. WAV should work on all platforms. I don't know what other combinations of platform/file format do or don't work - I haven't tried them yet.</p>
| 1 | 2016-01-25T02:24:09Z | [
"python",
"audio"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 36,115,093 | <p>Simply You can do it with the help of cvlc-
I did it in this way:</p>
<pre><code>import os
os.popen2("cvlc /home/maulo/selfProject/task.mp3 --play-and-exit")
</code></pre>
<p>/home/maulo/selfProject/task.mp3. This is the location of my mp3 file.
with the help of "--play-and-exit" you will be able to play again the sound without ending the vlc process.</p>
| 0 | 2016-03-20T14:41:10Z | [
"python",
"audio"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 36,284,043 | <p>Take a look at <a href="http://simpleaudio.readthedocs.org/en/latest/index.html" rel="nofollow">Simpleaudio</a>, which is a relatively recent and lightweight library for this purpose:</p>
<pre><code>> pip install simpleaudio
</code></pre>
<p>Then:</p>
<pre><code>import simpleaudio as sa
wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav")
play_obj = wave_obj.play()
play_obj.wait_done()
</code></pre>
<p>Make sure to use uncompressed 16 bit PCM files.</p>
| 1 | 2016-03-29T12:17:17Z | [
"python",
"audio"
] |
Play audio with Python | 260,738 | <p>How can I play audio (it would be like a 1 second sound) from a Python script?</p>
<p>It would be best if it was platform independent, but firstly it needs to work on a Mac.</p>
<p>I know I could just execute the <code>afplay file.mp3</code> command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.</p>
| 63 | 2008-11-04T03:11:03Z | 37,501,920 | <p>Throwing in another library into the bucket:</p>
<p><a href="https://github.com/bastibe/PySoundCard" rel="nofollow">https://github.com/bastibe/PySoundCard</a></p>
<p>PySoundCard uses PortAudio for playback which is available on many platforms.
In addition, it recognizes "professional" sound devices with lots of channels.</p>
<p>Worth a look!</p>
<p>Edit (as suggested):
Here a small example from the Readme:</p>
<pre><code>from pysoundcard import Stream
"""Loop back five seconds of audio data."""
fs = 44100
blocksize = 16
s = Stream(samplerate=fs, blocksize=blocksize)
s.start()
for n in range(int(fs*5/blocksize)):
s.write(s.read(blocksize))
s.stop()
</code></pre>
| 0 | 2016-05-28T17:30:18Z | [
"python",
"audio"
] |
How to build Python C extension modules with autotools | 261,500 | <p>Most of the documentation available for building Python extension modules
uses distutils, but I would like to achieve this by using the appropriate
python autoconf & automake macros instead.</p>
<p>I'd like to know if there is an open source project out there that does
exactly this. Most of the ones I've found end up relying on a setup.py file.
Using that approach works, but unfortunately ends up rebuilding the entire
source tree any time I make a modification to the module source files.</p>
| 7 | 2008-11-04T10:46:43Z | 261,839 | <p>All PyGTK extensions use autotools, so if the PyGTK aspects don't kill the whole thing for you, it might be worth having a look at the <a href="http://svn.gnome.org/viewvc/pygtk/trunk/" rel="nofollow">PyGTK source code</a>. Additionally, <a href="http://bazaar.launchpad.net/~poppler-python/poppler-python/trunk/files" rel="nofollow">here is one I wrote which is more simple.</a></p>
| 4 | 2008-11-04T13:10:44Z | [
"c++",
"python",
"c",
"autotools"
] |
How to build Python C extension modules with autotools | 261,500 | <p>Most of the documentation available for building Python extension modules
uses distutils, but I would like to achieve this by using the appropriate
python autoconf & automake macros instead.</p>
<p>I'd like to know if there is an open source project out there that does
exactly this. Most of the ones I've found end up relying on a setup.py file.
Using that approach works, but unfortunately ends up rebuilding the entire
source tree any time I make a modification to the module source files.</p>
| 7 | 2008-11-04T10:46:43Z | 13,711,218 | <p>Supposing that you have a project with a directory called <code>src</code>, so let's follow the follow steps to get a python extension built and packaged using autotools:</p>
<h2>Create the Makefile.am files</h2>
<p>First, you need to create one Makefile.am in the root of your project, basically (but not exclusively) listing the subdirectories that should also be processed. You will end up with something like this:</p>
<pre><code>SUBDIRS = src
</code></pre>
<p>The second one, inside the <code>src</code> directory will hold the instructions to actually compile your python extension. It will look like this:</p>
<pre><code>myextdir = $(pkgpythondir)
myext_PYTHON = file1.py file2.py
pyexec_LTLIBRARIES = _myext.la
_myext_la_SOURCES = myext.cpp
_myext_la_CPPFLAGS = $(PYTHON_CFLAGS)
_myext_la_LDFLAGS = -module -avoid-version -export-symbols-regex initmyext
_myext_la_LIBADD = $(top_builddir)/lib/libhollow.la
EXTRA_DIST = myext.h
</code></pre>
<h2>Write the configure.ac</h2>
<p>This file must be created in the root directory of the project and must list all libraries, programs or any kind of tool that your project needs to be built, such as a compiler, linker, libraries, etc.</p>
<p>Lazy people, like me, usually don't create it from scratch, I prefer to use the <code>autoscan</code> tool, that looks for things that you are using and generate a <code>configure.scan</code> file that can be used as the basis for your real <code>configure.ac</code>.</p>
<p>To inform <code>automake</code> that you will need python stuff, you can add this to your <code>configure.ac</code>:</p>
<pre><code>dnl python checks (you can change the required python version bellow)
AM_PATH_PYTHON(2.7.0)
PY_PREFIX=`$PYTHON -c 'import sys ; print sys.prefix'`
PYTHON_LIBS="-lpython$PYTHON_VERSION"
PYTHON_CFLAGS="-I$PY_PREFIX/include/python$PYTHON_VERSION"
AC_SUBST([PYTHON_LIBS])
AC_SUBST([PYTHON_CFLAGS])
</code></pre>
<h2>Wrap up</h2>
<p>Basically, <code>automake</code> has a built-in extension that knows how to deal with python stuff, you just need to add it to your <code>configure.ac</code> file and then take the advantage of this feature in your <code>Makefile.am</code>.</p>
<p>PyGtk is definitely an awesome example, but it's pretty big, so maybe you will want to check another project, like <a href="http://github.com/Guake/Guake">Guake</a></p>
| 11 | 2012-12-04T20:22:22Z | [
"c++",
"python",
"c",
"autotools"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 261,645 | <p>Python, being a byte-code-compiled interpreted language, is very difficult to lock down. Even if you use a exe-packager like <a href="http://py2exe.org">py2exe</a>, the layout of the executable is well-known, and the Python byte-codes are well understood.</p>
<p>Usually in cases like this, you have to make a tradeoff. How important is it really to protect the code? Are there real secrets in there (such as a key for symmetric encryption of bank transfers), or are you just being paranoid? Choose the language that lets you develop the best product quickest, and be realistic about how valuable your novel ideas are.</p>
<p>If you decide you really need to enforce the license check securely, write it as a small C extension so that the license check code can be extra-hard (but not impossible!) to reverse engineer, and leave the bulk of your code in Python.</p>
| 277 | 2008-11-04T12:00:34Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 261,704 | <p>You should take a look at how the guys at getdropbox.com do it for their client software, including Linux. It's quite tricky to crack and requires some quite creative disassembly to get past the protection mechanisms.</p>
| 5 | 2008-11-04T12:20:21Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 261,719 | <p>Is your employer aware that he can "steal" back any ideas that other people get from your code? I mean, if they can read your work, so can you theirs. Maybe looking at how you can benefit from the situation would yield a better return of your investment than fearing how much you could lose.</p>
<p>[EDIT] Answer to Nick's comment:</p>
<p>Nothing gained and nothing lost. The customer has what he wants (and paid for it since he did the change himself). Since he doesn't release the change, it's as if it didn't happen for everyone else.</p>
<p>Now if the customer sells the software, they have to change the copyright notice (which is illegal, so you can sue and will win -> simple case).</p>
<p>If they don't change the copyright notice, the 2nd level customers will notice that the software comes from you original and wonder what is going on. Chances are that they will contact you and so you will learn about the reselling of your work.</p>
<p>Again we have two cases: The original customer sold only a few copies. That means they didn't make much money anyway, so why bother. Or they sold in volume. That means better chances for you to learn about what they do and do something about it.</p>
<p>But in the end, most companies try to comply to the law (once their reputation is ruined, it's much harder to do business). So they will not steal your work but work with you to improve it. So if you include the source (with a license that protects you from simple reselling), chances are that they will simply push back changes they made since that will make sure the change is in the next version and they don't have to maintain it. That's win-win: You get changes and they can make the change themselves if they really, desperately need it even if you're unwilling to include it in the official release.</p>
| 30 | 2008-11-04T12:27:52Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 261,723 | <p>I have looked at software protection in general for my own projects and the general philosophy is that complete protection is impossible. The only thing that you can hope to achieve is to add protection to a level that would cost your customer more to bypass than it would to purchase another license.</p>
<p>With that said I was just checking google for python obsfucation and not turning up a lot of anything. In a .Net solution, obsfucation would be a first approach to your problem on a windows platform, but I am not sure if anyone has solutions on Linux that work with Mono. </p>
<p>The next thing would be to write your code in a compiled language, or if you really want to go all the way, then in assembler. A stripped out executable would be a lot harder to decompile than an interpreted language.</p>
<p>It all comes down to tradeoffs. On one end you have ease of software development in python, in which it is also very hard to hide secrets. On the other end you have software written in assembler which is much harder to write, but is much easier to hide secrets.</p>
<p>Your boss has to choose a point somewhere along that continuum that supports his requirements. And then he has to give you the tools and time so you can build what he wants. However my bet is that he will object to real development costs versus potential monetary losses.</p>
| 4 | 2008-11-04T12:28:38Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 261,727 | <p>"Is there a good way to handle this problem?" No. Nothing can be protected against reverse engineering. Even the firmware on DVD machines has been reverse engineered and <a href="http://en.wikipedia.org/wiki/AACS%5Fencryption%5Fkey%5Fcontroversy">AACS Encryption key</a> exposed. And that's in spite of the DMCA making that a criminal offense.</p>
<p>Since no technical method can stop your customers from reading your code, you have to apply ordinary commercial methods.</p>
<ol>
<li><p>Licenses. Contracts. Terms and Conditions. This still works even when people can read the code. Note that some of your Python-based components may require that you pay fees before you sell software using those components. Also, some open-source licenses prohibit you from concealing the source or origins of that component. </p></li>
<li><p>Offer significant value. If your stuff is so good -- at a price that is hard to refuse -- there's no incentive to waste time and money reverse engineering anything. Reverse engineering is expensive. Make your product slightly less expensive.</p></li>
<li><p>Offer upgrades and enhancements that make any reverse engineering a bad idea. When the next release breaks their reverse engineering, there's no point. This can be carried to absurd extremes, but you should offer new features that make the next release more valuable than reverse engineering.</p></li>
<li><p>Offer customization at rates so attractive that they'd rather pay you do build and support the enhancements.</p></li>
<li><p>Use a license key which expires. This is cruel, and will give you a bad reputation, but it certainly makes your software stop working. </p></li>
<li><p>Offer it as a web service. SaaS involves no downloads to customers. </p></li>
</ol>
| 395 | 2008-11-04T12:29:24Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 261,728 | <p>In some circumstances, it may be possible to move (all, or at least a key part) of the software into a web service that your organization hosts.</p>
<p>That way, the license checks can be performed in the safety of your own server room.</p>
| 12 | 2008-11-04T12:29:48Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 261,797 | <p>Depending in who the client is, a simple protection mechanism, combined with a sensible license agreement will be <em>far</em> more effective than any complex licensing/encryption/obfuscation system.</p>
<p>The best solution would be selling the code as a service, say by hosting the service, or offering support - although that isn't always practical.</p>
<p>Shipping the code as <code>.pyc</code> files will prevent your protection being foiled by a few <code>#</code>s, but it's hardly effective anti-piracy protection (as if there is such a technology), and at the end of the day, it shouldn't achieve anything that a decent license agreement with the company will.</p>
<p>Concentrate on making your code as nice to use as possible - having happy customers will make your company far more money than preventing some theoretical piracy..</p>
| 8 | 2008-11-04T12:53:25Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 261,808 | <p>What about signing your code with standard encryption schemes by hashing and signing important files and checking it with public key methods?</p>
<p>In this way you can issue license file with a public key for each customer.</p>
<p>Additional you can use an python obfuscator like <a href="http://www.lysator.liu.se/~astrand/projects/pyobfuscate/">this one</a> (just googled it).</p>
| 7 | 2008-11-04T12:59:04Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 261,817 | <h1>Python is not the tool you need</h1>
<p>You must use the right tool to do the right thing, and Python was not designed to be obfuscated. It's the contrary; everything is open or easy to reveal or modify in Python because that's the language's philosophy.</p>
<p>If you want something you can't see through, look for another tool. This is not a bad thing, it is important that several different tools exist for different usages.</p>
<h1>Obfuscation is really hard</h1>
<p>Even compiled programs can be reverse-engineered so don't think that you can fully protect any code. You can analyze obfuscated PHP, break the flash encryption key, etc. Newer versions of Windows are cracked every time.</p>
<h1>Having a legal requirement is a good way to go</h1>
<p>You cannot prevent somebody from misusing your code, but you can easily discover if someone does. Therefore, it's just a casual legal issue.</p>
<h1>Code protection is overrated</h1>
<p>Nowadays, business models tend to go for selling services instead of products. You cannot copy a service, pirate nor steal it. Maybe it's time to consider to go with the flow...</p>
| 289 | 2008-11-04T13:03:06Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 262,895 | <p>The best you can do with Python is to obscure things.</p>
<ul>
<li>Strip out all docstrings</li>
<li>Distribute only the .pyc compiled files.</li>
<li>freeze it</li>
<li>Obscure your constants inside a class/module so that help(config) doesn't show everything</li>
</ul>
<p>You may be able to add some additional obscurity by encrypting part of it and decrypting it on the fly and passing it to eval(). But no matter what you do someone can break it.</p>
<p>None of this will stop a determined attacker from disassembling the bytecode or digging through your api with help, dir, etc.</p>
| 5 | 2008-11-04T18:45:18Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 262,937 | <p>Do not rely on obfuscation. As You have correctly concluded, it offers very limited protection.
UPDATE: Here is a <a href="https://www.usenix.org/system/files/conference/woot13/woot13-kholia.pdf">link to paper</a> which reverse engineered obfuscated python code in Dropbox. The approach - opcode remapping is a good barrier, but clearly it can be defeated.</p>
<p>Instead, as many posters have mentioned make it:</p>
<ul>
<li>Not worth reverse engineering time (Your software is so good, it makes sense to pay)</li>
<li>Make them sign a contract and do a license audit if feasible. </li>
</ul>
<p>Alternatively, as the kick-ass Python IDE WingIDE does: <strong>Give away the code</strong>. That's right, give the code away and have people come back for upgrades and support.</p>
| 19 | 2008-11-04T18:53:11Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 263,314 | <p>The reliable only way to protect code is to run it on a server you control and provide your clients with a client which interfaces with that server.</p>
| 7 | 2008-11-04T20:27:05Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 264,450 | <p>Though there's no perfect solution, the following can be done:</p>
<ol>
<li>Move some critical piece of startup code into a native library.</li>
<li>Enforce the license check in the native library.</li>
</ol>
<p>If the call to the native code were to be removed, the program wouldn't start anyway. If it's not removed then the license will be enforced.</p>
<p>Though this is not a cross-platform or a pure-Python solution, it will work.</p>
| 13 | 2008-11-05T06:10:26Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 267,875 | <p>I understand that you want your customers to use the power of python but do not want expose the source code.</p>
<p>Here are my suggestions:</p>
<p>(a) Write the critical pieces of the code as C or C++ libraries and then use <a href="http://www.riverbankcomputing.co.uk/software/sip/intro">SIP</a> or <a href="http://www.swig.org/">swig</a> to expose the C/C++ APIs to Python namespace.</p>
<p>(b) Use <a href="http://cython.org/">cython</a> instead of Python</p>
<p>(c) In both (a) and (b), it should be possible to distribute the libraries as licensed binary with a Python interface.</p>
| 52 | 2008-11-06T07:41:59Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 554,565 | <p>Shipping .pyc files has its problems - they are not compatible with any other python version than the python version they were created with, which means you must know which python version is running on the systems the product will run on. That's a very limiting factor.</p>
| 11 | 2009-02-16T21:09:33Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 827,080 | <p>Another attempt to make your code harder to steal is to use jython and then use <a href="http://proguard.sourceforge.net/">java obfuscator</a>. </p>
<p>This should work pretty well as jythonc translate python code to java and then java is compiled to bytecode. So ounce you obfuscate the classes it will be really hard to understand what is going on after decompilation, not to mention recovering the actual code. </p>
<p>The only problem with jython is that you can't use python modules written in c.</p>
| 8 | 2009-05-05T21:53:15Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 2,987,179 | <p>Idea of having time restricted license and check for it in locally installed program will not work. Even with perfect obfuscation, license check can be removed. However if you check license on remote system and run significant part of the program on your closed remote system, you will be able to protect your IP.</p>
<p>Preventing competitors from using the source code as their own or write their inspired version of the same code, one way to protect is to add signatures to your program logic (some secrets to be able to prove that code was stolen from you) and obfuscate the python source code so, it's hard to read and utilize. </p>
<p>Good obfuscation adds basically the same protection to your code, that compiling it to executable (and stripping binary) does. Figuring out how obfuscated complex code works might be even harder than actually writing your own implementation. </p>
<p>This will not help preventing hacking of your program. Even with obfuscation code license stuff will be cracked and program may be modified to have slightly different behaviour (in the same way that compiling code to binary does not help protection of native programs). </p>
<p>In addition to symbol obfuscation might be good idea to unrefactor the code, which makes everything even more confusing if e.g. call graphs points to many different places even if actually those different places does eventually the same thing. </p>
<p>Logical signature inside obfuscated code (e.g. you may create table of values which are used by program logic, but also used as signature), which can be used to determine that code is originated from you. If someone decides to use your obfuscated code module as part of their own product (even after reobfuscating it to make it seem different) you can show, that code is stolen with your secret signature.</p>
| 4 | 2010-06-07T05:07:06Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 7,347,168 | <h2>Compile python and distribute binaries!</h2>
<p><strong>Sensible idea:</strong> </p>
<p>Use <a href="http://cython.org/">Cython</a> (or something similar) to compile python to C code, then distribute your app as python binary libraries (pyd) instead.</p>
<p>That way, no Python (byte) code is left and you've done any reasonable amount of obscurification anyone (i.e. your employer) could expect from regular Code, I think. (.NET or Java less safe than this case, as that bytecode is not obfuscated and can relatively easily be decompiled into reasonable source.)</p>
<p>Cython is getting more and more compatible with CPython, so I think it should work. (I'm actually considering this for our product.. We're already building some thirdparty libs as pyd/dlls, so shipping our own python code as binaries is not a overly big step for us.)</p>
<p>See <a href="http://blog.biicode.com/bii-internals-compiling-your-python-application-with-cython/">This Blog Post</a> (not by me) for a tutorial on how to do it. (thx @hithwen)</p>
<p><strong>Crazy idea:</strong></p>
<p>You could probably get Cython to store the C-files separately for each module, then just concatenate them all and build them with heavy inlining. That way, your Python module is pretty monolithic and difficult to chip at with common tools.</p>
<p><strong>Beyond crazy:</strong></p>
<p>You might be able to build a single executable if you can link to (and optimize with) the python runtime and all libraries (dlls) statically. That way, it'd sure be difficult to intercept calls to/from python and whatever framework libraries you use. This cannot be done if you're using LGPL code though.</p>
| 83 | 2011-09-08T11:14:04Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 9,547,169 | <p>using cxfreeze ( py2exe for linux ) will do the job.</p>
<p><a href="http://cx-freeze.sourceforge.net/" rel="nofollow">http://cx-freeze.sourceforge.net/</a></p>
<p>it is available in ubuntu repositories</p>
| 3 | 2012-03-03T15:13:13Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 10,593,293 | <p><a href="http://www.bitboost.com" rel="nofollow">www.bitboost.com</a> offers a python obfuscator. Full disclosure: the author is a friend of mine.</p>
| 4 | 2012-05-15T02:00:40Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 11,315,793 | <p>I think there is one more method to protect your Python code; part of the Obfuscation method. I beleive there was a game like Mount and Blade or something that changed and recompiled their own python interpreter (the original interpreter which i believe is open source) and just changed the OP codes in the OP code table to be different then the standard python OP codes.</p>
<p>So the python source is unmodified but the file extentions of the pyc files are different and the op codes don't match to the public python.exe interpreter. If you checked the games data files all the data was in Python source format.</p>
<p>All sorts of nasty tricks can be done to mess with amature hackers this way. Stopping a bunch of noob hackers is easy. It's the pro hackers that you will not likely beat. But most companies don't keep pro hackers on staff long I imagine (likely because things get hacked). But amature hackers are all over the place (read as curious IT staff).</p>
<p>You could for example, in a modified interpreter, allow it to check for certain comments or docstrings in your source. You could have special OP codes for such lines of code. For example:</p>
<p>OP 234 is for source line "# Copyright I wrote this"
or compile that line into op codes that are equivelent to "if False:" if "# Copyright" is missing. Basically disabling a whole block of code for what appears to be some obsure reason.</p>
<p>One use case where recompiling a modified interpreter may be feasable is where you didn't write the app, the app is big, but you are paid to protect it, such as when you're a dedicated server admin for a financial app.</p>
<p>I find it a little contradictory to leave the source or opcodes open for eyeballs, but use SSL for network traffic. SSL is not 100% safe either. But it's used to stop MOST eyes from reading it. A wee bit precaution is sensible.</p>
<p>Also, if enough people deem that Python source and opcodes are too visible, it's likely someone will eventually develope at least a simple protection tool for it. So the more people asking "how to protect Python app" only promotes that development.</p>
| 8 | 2012-07-03T17:07:27Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 16,695,056 | <p>It is possible to have the py2exe byte-code in a crypted resource for a C launcher that loads and executes it in memory. Some ideas <a href="http://evilzone.org/hacking-and-security/encrypting-programs-how-does-that-work/10/?wap2" rel="nofollow">here</a> and <a href="http://bubblews.com/news/430170-crypter-small-guide" rel="nofollow">here</a>.</p>
<p>Some have also thought of <a href="http://cosic.esat.kuleuven.be/publications/article-1529.pdf" rel="nofollow">a self modifying program</a> to make reverse engineering expensive.</p>
<p>You can also find <a href="http://resources.infosecinstitute.com/anti-debugging/" rel="nofollow">tutorials for preventing debuggers</a>, make the disassembler fail, set <a href="http://bases-hacking.org/protection-executables.html" rel="nofollow">false debugger breakpoints</a> and protect your code with checksums. Search for ["crypted code" execute "in memory"] for more links.</p>
<p>But as others already said, if your code is worth it, reverse engineers will succeed in the end.</p>
| 3 | 2013-05-22T14:53:50Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
How do I protect Python code? | 261,638 | <p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file.</p>
<p>If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem? Preferably with an off-the-shelf solution.</p>
<p>The software will run on Linux systems (so I don't think py2exe will do the trick).</p>
| 408 | 2008-11-04T11:57:27Z | 30,121,460 | <p>Have you had a look at <a href="https://liftoff.github.io/pyminifier/">pyminifier</a>? It does Minify, obfuscate, and compress Python code. The example code looks pretty nasty for casual reverse engineering.</p>
<pre><code>$ pyminifier --nonlatin --replacement-length=50 /tmp/tumult.py
#!/usr/bin/env python3
ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²ï¬¾=ImportError
ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²ç±=print
ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²í¡¾í²=False
ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²æ¾¨=object
try:
import demiurgic
except ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²ï¬¾:
ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²ç±("Warning: You're not demiurgic. Actually, I think that's normal.")
try:
import mystificate
except ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²ï¬¾:
ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²ç±("Warning: Dark voodoo may be unreliable.")
ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²ïº¬=ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²í¡¾í²
class ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²í í¶(ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²æ¾¨):
def __init__(self,*args,**kwargs):
pass
def ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²í´(self,dactyl):
ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²í=demiurgic.palpitation(dactyl)
ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²í¡í»²=mystificate.dark_voodoo(ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²í)
return ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²í¡í»²
def ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²í í°¯(self,whatever):
ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²ç±(whatever)
if __name__=="__main__":
ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²ç±("Forming...")
ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²ïº=ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²í í¶("epicaricacy","perseverate")
ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²ïº.ïºå¼í »í¸í í´ïï°£ïºÚºí µíµí¡£í¿©í »í¸ë»í í¼í¡í°«å¬ï±í¡í½í í±í¡íº®êªï´¹ë«í¡í´´íﳦﲣïÜﺶí í°¤ï¶¨à í í°·í¡í±¶í¡í°í í½í »í¸í¡í²í¡í¸¼ï¶»í¡¤í¿í¡í½¨í »íºí¡í»í í°²äï°¸ï³á£²í í°¯("Codswallop")
# Created by pyminifier (https://github.com/liftoff/pyminifier)
</code></pre>
| 9 | 2015-05-08T10:21:58Z | [
"python",
"licensing",
"obfuscation",
"copy-protection"
] |
Converting a List of Tuples into a Dict in Python | 261,655 | <p>I have a list of tuples like this:</p>
<pre><code>[
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
</code></pre>
<p>I want to iterate through this keying by the first item, so for example I could print something like this:</p>
<pre><code>a 1 2 3
b 1 2
c 1
</code></pre>
<p>How would I go about doing this without keeping an item to track whether the first item is the same as I loop round the tuples. This feels rather messy (plus I have to sort the list to start with)...</p>
<p>Thanks,</p>
<p>Dan</p>
| 29 | 2008-11-04T12:03:34Z | 261,665 | <pre><code>l = [
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
d = {}
for x, y in l:
d.setdefault(x, []).append(y)
print d
</code></pre>
<p>produces:</p>
<pre><code>{'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}
</code></pre>
| 27 | 2008-11-04T12:07:21Z | [
"python",
"data-structures",
"iteration"
] |
Converting a List of Tuples into a Dict in Python | 261,655 | <p>I have a list of tuples like this:</p>
<pre><code>[
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
</code></pre>
<p>I want to iterate through this keying by the first item, so for example I could print something like this:</p>
<pre><code>a 1 2 3
b 1 2
c 1
</code></pre>
<p>How would I go about doing this without keeping an item to track whether the first item is the same as I loop round the tuples. This feels rather messy (plus I have to sort the list to start with)...</p>
<p>Thanks,</p>
<p>Dan</p>
| 29 | 2008-11-04T12:03:34Z | 261,677 | <p>Slightly simpler...</p>
<pre><code>>>> from collections import defaultdict
>>> fq= defaultdict( list )
>>> for n,v in myList:
fq[n].append(v)
>>> fq
defaultdict(<type 'list'>, {'a': [1, 2, 3], 'c': [1], 'b': [1, 2]})
</code></pre>
| 23 | 2008-11-04T12:11:52Z | [
"python",
"data-structures",
"iteration"
] |
Converting a List of Tuples into a Dict in Python | 261,655 | <p>I have a list of tuples like this:</p>
<pre><code>[
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
</code></pre>
<p>I want to iterate through this keying by the first item, so for example I could print something like this:</p>
<pre><code>a 1 2 3
b 1 2
c 1
</code></pre>
<p>How would I go about doing this without keeping an item to track whether the first item is the same as I loop round the tuples. This feels rather messy (plus I have to sort the list to start with)...</p>
<p>Thanks,</p>
<p>Dan</p>
| 29 | 2008-11-04T12:03:34Z | 261,766 | <p>A solution using groupby</p>
<pre><code> >>> from itertools import groupby
>>> l = [('a',1), ('a', 2),('a', 3),('b', 1),('b', 2),('c', 1),]
>>> [(label, [v for l,v in value]) for (label, value) in groupby(l, lambda x:x[0])]
[('a', [1, 2, 3]), ('b', [1, 2]), ('c', [1])]
</code></pre>
<p>groupby(l, lambda x:x[0]) gives you an iterator that contains ['a', [('a', 1), ...], c, [('c', 1)], ...]</p>
| 8 | 2008-11-04T12:42:32Z | [
"python",
"data-structures",
"iteration"
] |
Converting a List of Tuples into a Dict in Python | 261,655 | <p>I have a list of tuples like this:</p>
<pre><code>[
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
</code></pre>
<p>I want to iterate through this keying by the first item, so for example I could print something like this:</p>
<pre><code>a 1 2 3
b 1 2
c 1
</code></pre>
<p>How would I go about doing this without keeping an item to track whether the first item is the same as I loop round the tuples. This feels rather messy (plus I have to sort the list to start with)...</p>
<p>Thanks,</p>
<p>Dan</p>
| 29 | 2008-11-04T12:03:34Z | 262,530 | <p>I would just do the basic</p>
<pre>
answer = {}
for key, value in list_of_tuples:
if key in answer:
answer[key].append(value)
else:
answer[key] = [value]
</pre>
<p>If it's this short, why use anything complicated. Of course if you don't mind using setdefault that's okay too.</p>
| 1 | 2008-11-04T17:06:28Z | [
"python",
"data-structures",
"iteration"
] |
Converting a List of Tuples into a Dict in Python | 261,655 | <p>I have a list of tuples like this:</p>
<pre><code>[
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
</code></pre>
<p>I want to iterate through this keying by the first item, so for example I could print something like this:</p>
<pre><code>a 1 2 3
b 1 2
c 1
</code></pre>
<p>How would I go about doing this without keeping an item to track whether the first item is the same as I loop round the tuples. This feels rather messy (plus I have to sort the list to start with)...</p>
<p>Thanks,</p>
<p>Dan</p>
| 29 | 2008-11-04T12:03:34Z | 1,694,768 | <h3>Print list of tuples grouping by the first item</h3>
<p>This answer is based on <a href="http://stackoverflow.com/questions/261655/converting-a-list-of-tuples-into-a-dict-in-python/261766#261766">the @gommen one</a>.</p>
<pre><code>#!/usr/bin/env python
from itertools import groupby
from operator import itemgetter
L = [
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
key = itemgetter(0)
L.sort(key=key) #NOTE: use `L.sort()` if you'd like second items to be sorted too
for k, group in groupby(L, key=key):
print k, ' '.join(str(item[1]) for item in group)
</code></pre>
<p>Output:</p>
<pre><code>a 1 2 3
b 1 2
c 1
</code></pre>
| 1 | 2009-11-07T23:11:33Z | [
"python",
"data-structures",
"iteration"
] |
How do I safely decode a degrees symbol in a wxPython app? | 262,249 | <p>I have a debug app I've been writing which receives data from a C-based process via UDP. One of the strings sent to me contains a <code>°</code> character - <a href="http://en.wikipedia.org/wiki/Degree_symbol" rel="nofollow">Unicode U+00B0</a> (which incidentally breaks the StackOverflow search function!). When my wxPython application tries to append that string to a text box I get a <code>UnicodeDecodeError</code>.</p>
<p>My first attempt to fix the issue simply caught that error (because the app apparently does send <em>some</em> bad messages. The problem is that the app also uses the character to report various temperatures around the unit and that's something we really need to log. Changing the source app is out of my control, so how can I detect and decode those symbols into something the <code>wxTextCtrl</code> can display?</p>
| 0 | 2008-11-04T16:07:01Z | 262,433 | <p>I can't say mych about wxPython itself, but I am guessing that it is trying to convert the text to Unicode before displaying it, If you have a string like <code>'123\xB0'</code> and try to convert it to Unicode with teh default encoding (ASCII) then it will throw <code>UnicodeDecodeError</code>. You can probably fix this by replacing </p>
<pre><code>s = message.get_string()
</code></pre>
<p>with </p>
<pre><code>s = message.get_string().decode('ISO8859-1')
</code></pre>
<p>(where I am assuming a function <code>get_string()</code> that gets the message as a string). The difference here is that by handong the conversion to Unicode yourself you get to specify the encoding.</p>
| 1 | 2008-11-04T16:48:22Z | [
"python",
"unicode",
"wxpython",
"decode",
"textctrl"
] |
How do I safely decode a degrees symbol in a wxPython app? | 262,249 | <p>I have a debug app I've been writing which receives data from a C-based process via UDP. One of the strings sent to me contains a <code>°</code> character - <a href="http://en.wikipedia.org/wiki/Degree_symbol" rel="nofollow">Unicode U+00B0</a> (which incidentally breaks the StackOverflow search function!). When my wxPython application tries to append that string to a text box I get a <code>UnicodeDecodeError</code>.</p>
<p>My first attempt to fix the issue simply caught that error (because the app apparently does send <em>some</em> bad messages. The problem is that the app also uses the character to report various temperatures around the unit and that's something we really need to log. Changing the source app is out of my control, so how can I detect and decode those symbols into something the <code>wxTextCtrl</code> can display?</p>
| 0 | 2008-11-04T16:07:01Z | 263,330 | <p>pdc got it right, the following works fine (but fails without the <code>decode</code>):</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
app = wx.PySimpleApp()
app.TopWindow = wx.Frame(None)
field = wx.TextCtrl(app.TopWindow)
field.Value += '°'.decode('ISO8859-1')
app.TopWindow.Show()
app.MainLoop()
</code></pre>
| 2 | 2008-11-04T20:34:13Z | [
"python",
"unicode",
"wxpython",
"decode",
"textctrl"
] |
How do I safely decode a degrees symbol in a wxPython app? | 262,249 | <p>I have a debug app I've been writing which receives data from a C-based process via UDP. One of the strings sent to me contains a <code>°</code> character - <a href="http://en.wikipedia.org/wiki/Degree_symbol" rel="nofollow">Unicode U+00B0</a> (which incidentally breaks the StackOverflow search function!). When my wxPython application tries to append that string to a text box I get a <code>UnicodeDecodeError</code>.</p>
<p>My first attempt to fix the issue simply caught that error (because the app apparently does send <em>some</em> bad messages. The problem is that the app also uses the character to report various temperatures around the unit and that's something we really need to log. Changing the source app is out of my control, so how can I detect and decode those symbols into something the <code>wxTextCtrl</code> can display?</p>
| 0 | 2008-11-04T16:07:01Z | 13,496,753 | <p>Things may have been different back when this was asked, but my thoughts for anyone who stumbles on this:</p>
<p>The issue is wxPython is trying to convert TO unicode, and lacking charset information it tries to use ASCII, which is invalid. If you know your data is utf-8, tell it so and it'll just work.</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
app = wx.PySimpleApp()
app.TopWindow = wx.Frame(None)
field = wx.TextCtrl(app.TopWindow)
string_data = '°'
print type(string_data)
# this would error, as it tries to convert to unicode from ascii
# field.Value += string_data
unicode_data = unicode(string_data, 'utf-8')
print type(unicode_data)
field.Value += unicode_data
app.TopWindow.Show()
app.MainLoop()
</code></pre>
| 0 | 2012-11-21T15:42:08Z | [
"python",
"unicode",
"wxpython",
"decode",
"textctrl"
] |
making a programme run indefinitely in python | 262,460 | <p>Is there any way to make a function (the ones I'm thinking of are in the style of the simple ones I've made which generate the fibonnacci sequence from 0 to a point, and all the primes between two points) run indefinitely. E.g. until I press a certain key or until a time has passed, rather than until a number reaches a certain point? </p>
<p>Also, if it is based on time then is there any way I could just extend the time and start it going from that point again, rather than having to start again from 0? I am aware there is a time module, i just don't know much about it.</p>
| 0 | 2008-11-04T16:53:45Z | 262,474 | <p>As in almost all languages:</p>
<pre><code>while True:
# check what you want and eventually break
print nextValue()
</code></pre>
<p>The second part of your question is more interesting:</p>
<blockquote>
<p>Also, if it is based on time then is there anyway I could just extend the time and start it going from that point again rather than having to start again from 0</p>
</blockquote>
<p>you can use a <code>yield</code> instead of <code>return</code> in the function <code>nextValue()</code></p>
| 0 | 2008-11-04T16:55:50Z | [
"python",
"time",
"key",
"indefinite"
] |
making a programme run indefinitely in python | 262,460 | <p>Is there any way to make a function (the ones I'm thinking of are in the style of the simple ones I've made which generate the fibonnacci sequence from 0 to a point, and all the primes between two points) run indefinitely. E.g. until I press a certain key or until a time has passed, rather than until a number reaches a certain point? </p>
<p>Also, if it is based on time then is there any way I could just extend the time and start it going from that point again, rather than having to start again from 0? I am aware there is a time module, i just don't know much about it.</p>
| 0 | 2008-11-04T16:53:45Z | 262,490 | <p>The simplest way is just to write a program with an infinite loop, and then hit control-C to stop it. Without more description it's hard to know if this works for you.</p>
<p>If you do it time-based, you don't need a generator. You can just have it pause for user input, something like a "Continue? [y/n]", read from stdin, and depending on what you get either exit the loop or not.</p>
| 1 | 2008-11-04T16:58:14Z | [
"python",
"time",
"key",
"indefinite"
] |
making a programme run indefinitely in python | 262,460 | <p>Is there any way to make a function (the ones I'm thinking of are in the style of the simple ones I've made which generate the fibonnacci sequence from 0 to a point, and all the primes between two points) run indefinitely. E.g. until I press a certain key or until a time has passed, rather than until a number reaches a certain point? </p>
<p>Also, if it is based on time then is there any way I could just extend the time and start it going from that point again, rather than having to start again from 0? I am aware there is a time module, i just don't know much about it.</p>
| 0 | 2008-11-04T16:53:45Z | 262,520 | <p>If you use a child thread to run the function while the main thread waits for character input it should work. Just remember to have something that stops the child thread (in the example below the global runthread)</p>
<p>For example:</p>
<pre><code>import threading, time
runthread = 1
def myfun():
while runthread:
print "A"
time.sleep(.1)
t = threading.Thread(target=myfun)
t.start()
raw_input("")
runthread = 0
t.join()
</code></pre>
<p>does just that</p>
| 0 | 2008-11-04T17:04:28Z | [
"python",
"time",
"key",
"indefinite"
] |
making a programme run indefinitely in python | 262,460 | <p>Is there any way to make a function (the ones I'm thinking of are in the style of the simple ones I've made which generate the fibonnacci sequence from 0 to a point, and all the primes between two points) run indefinitely. E.g. until I press a certain key or until a time has passed, rather than until a number reaches a certain point? </p>
<p>Also, if it is based on time then is there any way I could just extend the time and start it going from that point again, rather than having to start again from 0? I am aware there is a time module, i just don't know much about it.</p>
| 0 | 2008-11-04T16:53:45Z | 262,542 | <p>If you really want your function to run and still wants user (or system) input, you have two solutions:</p>
<ol>
<li>multi-thread</li>
<li>multi-process</li>
</ol>
<p>It will depend on how fine the interaction. If you just want to interrupt the function and don't care about the exit, then multi-process is fine.</p>
<p>In both cases, you can rely on some shared resources (file or shared memory for multi-thread, variable with associated mutex for multi-thread) and check for the state of that resource regularly in your function. If it is set up to tell you to quit, just do it.</p>
<p>Example on multi-thread:</p>
<pre><code>from threading import Thread, Lock
from time import sleep
class MyFct(Thread):
def __init__(self):
Thread.__init__(self)
self.mutex = Lock()
self._quit = False
def stopped(self):
self.mutex.acquire()
val = self._quit
self.mutex.release()
return val
def stop(self):
self.mutex.acquire()
self._quit = True
self.mutex.release()
def run(self):
i = 1
j = 1
print i
print j
while True:
if self.stopped():
return
i,j = j,i+j
print j
def main_fct():
t = MyFct()
t.start()
sleep(1)
t.stop()
t.join()
print "Exited"
if __name__ == "__main__":
main_fct()
</code></pre>
| 0 | 2008-11-04T17:10:49Z | [
"python",
"time",
"key",
"indefinite"
] |
making a programme run indefinitely in python | 262,460 | <p>Is there any way to make a function (the ones I'm thinking of are in the style of the simple ones I've made which generate the fibonnacci sequence from 0 to a point, and all the primes between two points) run indefinitely. E.g. until I press a certain key or until a time has passed, rather than until a number reaches a certain point? </p>
<p>Also, if it is based on time then is there any way I could just extend the time and start it going from that point again, rather than having to start again from 0? I am aware there is a time module, i just don't know much about it.</p>
| 0 | 2008-11-04T16:53:45Z | 262,852 | <p>If you want to exit based on time, you can use the signal module's alarm(time) function, and the catch the SIGALRM - here's an example <a href="http://docs.python.org/library/signal.html#example" rel="nofollow">http://docs.python.org/library/signal.html#example</a></p>
<p>You can let the user interrupt the program in a sane manner by catching KeyboardInterrupt. Simply catch the KeyboardInterrupt exception from outside you main loop, and do whatever cleanup you want.</p>
<p>If you want to continue later where you left off, you will have to add some sort persistence. I would <a href="http://docs.python.org/library/pickle.html#module-pickle" rel="nofollow">pickle</a> a data structure to disk, that you could read back in to continue the operations. </p>
<p>I haven't tried anything like this, but you could look into using something like <a href="http://wiki.python.org/moin/PythonDecoratorLibrary#head-11870a08b0fa59a8622201abfac735ea47ffade5" rel="nofollow">memoizing</a>, and caching to the disk.</p>
| 0 | 2008-11-04T18:29:31Z | [
"python",
"time",
"key",
"indefinite"
] |
making a programme run indefinitely in python | 262,460 | <p>Is there any way to make a function (the ones I'm thinking of are in the style of the simple ones I've made which generate the fibonnacci sequence from 0 to a point, and all the primes between two points) run indefinitely. E.g. until I press a certain key or until a time has passed, rather than until a number reaches a certain point? </p>
<p>Also, if it is based on time then is there any way I could just extend the time and start it going from that point again, rather than having to start again from 0? I am aware there is a time module, i just don't know much about it.</p>
| 0 | 2008-11-04T16:53:45Z | 263,876 | <p>You could do something like this to generate fibonnacci numbers for 1 second then stop.</p>
<pre><code>fibonnacci = [1,1]
stoptime = time.time() + 1 # set stop time to 1 second in the future
while time.time() < stoptime:
fibonnacci.append(fibonnacci[-1]+fibonnacci[-2])
print "Generated %s numbers, the last one was %s." % (len(fibonnacci),fibonnacci[-1])
</code></pre>
<p>I'm not sure how efficient it is to call time.time() in every loop - depending on the what you are doing inside the loop, it might end up taking a lot of the performance away.</p>
| -1 | 2008-11-04T23:27:14Z | [
"python",
"time",
"key",
"indefinite"
] |
making a programme run indefinitely in python | 262,460 | <p>Is there any way to make a function (the ones I'm thinking of are in the style of the simple ones I've made which generate the fibonnacci sequence from 0 to a point, and all the primes between two points) run indefinitely. E.g. until I press a certain key or until a time has passed, rather than until a number reaches a certain point? </p>
<p>Also, if it is based on time then is there any way I could just extend the time and start it going from that point again, rather than having to start again from 0? I am aware there is a time module, i just don't know much about it.</p>
| 0 | 2008-11-04T16:53:45Z | 264,614 | <p>You could use a generator for this:</p>
<pre><code>def finished():
"Define your exit condition here"
return ...
def count(i=0):
while not finished():
yield i
i += 1
for i in count():
print i
</code></pre>
<p>If you want to change the exit condition you could pass a value back into the generator function and use that value to determine when to exit.</p>
| 0 | 2008-11-05T08:33:49Z | [
"python",
"time",
"key",
"indefinite"
] |
Is it possible to change the Environment of a parent process in python? | 263,005 | <p>In Linux When I invoke python from the shell it replicates its environment, and starts the python process. Therefore if I do something like the following:</p>
<pre><code>import os
os.environ["FOO"] = "A_Value"
</code></pre>
<p>When the python process returns, FOO, assuming it was undefined originally, will still be undefined. Is there a way for the python process (or any child process) to modify the environment of its parent process?</p>
<p>I know you typically solve this problem using something like</p>
<pre><code>source script_name.sh
</code></pre>
<p>But this conflicts with other requirements I have.</p>
| 11 | 2008-11-04T19:08:16Z | 263,022 | <p>It's not possible, for any child process, to change the environment of the parent process. The best you can do is to output shell statements to stdout that you then source, or write it to a file that you source in the parent.</p>
| 11 | 2008-11-04T19:12:44Z | [
"python",
"linux",
"environment"
] |
Is it possible to change the Environment of a parent process in python? | 263,005 | <p>In Linux When I invoke python from the shell it replicates its environment, and starts the python process. Therefore if I do something like the following:</p>
<pre><code>import os
os.environ["FOO"] = "A_Value"
</code></pre>
<p>When the python process returns, FOO, assuming it was undefined originally, will still be undefined. Is there a way for the python process (or any child process) to modify the environment of its parent process?</p>
<p>I know you typically solve this problem using something like</p>
<pre><code>source script_name.sh
</code></pre>
<p>But this conflicts with other requirements I have.</p>
| 11 | 2008-11-04T19:08:16Z | 263,068 | <p>No process can change its parent process (or any other existing process' environment).</p>
<p>You can, however, create a new environment by creating a new interactive shell with the modified environment.</p>
<p>You have to spawn a new copy of the shell that uses the upgraded environment and has access to the existing stdin, stdout and stderr, and does its reinitialization dance.</p>
<p>You need to do something like use subprocess.Popen to run <code>/bin/bash -i</code>.</p>
<p>So the original shell runs Python, which runs a new shell. Yes, you have a lot of processes running. No it's not too bad because the original shell and Python aren't really doing anything except waiting for the subshell to finish so they can exit cleanly, also.</p>
| 9 | 2008-11-04T19:27:27Z | [
"python",
"linux",
"environment"
] |
Is it possible to change the Environment of a parent process in python? | 263,005 | <p>In Linux When I invoke python from the shell it replicates its environment, and starts the python process. Therefore if I do something like the following:</p>
<pre><code>import os
os.environ["FOO"] = "A_Value"
</code></pre>
<p>When the python process returns, FOO, assuming it was undefined originally, will still be undefined. Is there a way for the python process (or any child process) to modify the environment of its parent process?</p>
<p>I know you typically solve this problem using something like</p>
<pre><code>source script_name.sh
</code></pre>
<p>But this conflicts with other requirements I have.</p>
| 11 | 2008-11-04T19:08:16Z | 263,162 | <p>I would use the bash eval statement, and have the python script output the shell code</p>
<p>child.py:</p>
<pre><code>#!/usr/bin/env python
print 'FOO="A_Value"'
</code></pre>
<p>parent.sh</p>
<pre><code>#!/bin/bash
eval `./child.py`
</code></pre>
| 7 | 2008-11-04T19:41:03Z | [
"python",
"linux",
"environment"
] |
Creating a python win32 service | 263,296 | <p>I am currently trying to create a win32 service using pywin32. My main point of reference has been this tutorial:</p>
<p><a href="http://code.activestate.com/recipes/551780/">http://code.activestate.com/recipes/551780/</a></p>
<p>What i don't understand is the initialization process, since the Daemon is never initialized directly by Daemon(), instead from my understanding its initialized by the following:</p>
<pre><code>mydaemon = Daemon
__svc_regClass__(mydaemon, "foo", "foo display", "foo description")
__svc_install__(mydaemon)
</code></pre>
<p>Where <strong>svc_install</strong>, handles the initalization, by calling Daemon.<strong>init</strong>() and passing some arguments to it. </p>
<p>But how can i initialize the daemon object, without initalizing the service? I want to do a few things, before i init the service. Does anyone have any ideas?</p>
<pre><code>class Daemon(win32serviceutil.ServiceFramework):
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcDoRun(self):
self.run()
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def start(self):
pass
def stop(self):
self.SvcStop()
def run(self):
pass
def __svc_install__(cls):
win32api.SetConsoleCtrlHandler(lambda x: True, True)
try:
win32serviceutil.InstallService(
cls._svc_reg_class_,
cls._svc_name_,
cls._svc_display_name_,
startType = win32service.SERVICE_AUTO_START
)
print "Installed"
except Exception, err:
print str(err)
def __svc_regClass__(cls, name, display_name, description):
#Bind the values to the service name
cls._svc_name_ = name
cls._svc_display_name_ = display_name
cls._svc_description_ = description
try:
module_path = sys.modules[cls.__module__].__file__
except AttributeError:
from sys import executable
module_path = executable
module_file = os.path.splitext(os.path.abspath(module_path))[0]
cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__)
</code></pre>
| 11 | 2008-11-04T20:23:17Z | 264,871 | <p>I've never used these APIs, but digging through the code, it looks like the class passed in is used to register the name of the class in the registry, so you can't do any initialization of your own. But there's a method called GetServiceCustomOption that may help:</p>
<p><a href="http://mail.python.org/pipermail/python-win32/2006-April/004518.html">http://mail.python.org/pipermail/python-win32/2006-April/004518.html</a></p>
| 5 | 2008-11-05T11:18:14Z | [
"python",
"winapi",
"pywin32"
] |
Creating a python win32 service | 263,296 | <p>I am currently trying to create a win32 service using pywin32. My main point of reference has been this tutorial:</p>
<p><a href="http://code.activestate.com/recipes/551780/">http://code.activestate.com/recipes/551780/</a></p>
<p>What i don't understand is the initialization process, since the Daemon is never initialized directly by Daemon(), instead from my understanding its initialized by the following:</p>
<pre><code>mydaemon = Daemon
__svc_regClass__(mydaemon, "foo", "foo display", "foo description")
__svc_install__(mydaemon)
</code></pre>
<p>Where <strong>svc_install</strong>, handles the initalization, by calling Daemon.<strong>init</strong>() and passing some arguments to it. </p>
<p>But how can i initialize the daemon object, without initalizing the service? I want to do a few things, before i init the service. Does anyone have any ideas?</p>
<pre><code>class Daemon(win32serviceutil.ServiceFramework):
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcDoRun(self):
self.run()
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def start(self):
pass
def stop(self):
self.SvcStop()
def run(self):
pass
def __svc_install__(cls):
win32api.SetConsoleCtrlHandler(lambda x: True, True)
try:
win32serviceutil.InstallService(
cls._svc_reg_class_,
cls._svc_name_,
cls._svc_display_name_,
startType = win32service.SERVICE_AUTO_START
)
print "Installed"
except Exception, err:
print str(err)
def __svc_regClass__(cls, name, display_name, description):
#Bind the values to the service name
cls._svc_name_ = name
cls._svc_display_name_ = display_name
cls._svc_description_ = description
try:
module_path = sys.modules[cls.__module__].__file__
except AttributeError:
from sys import executable
module_path = executable
module_file = os.path.splitext(os.path.abspath(module_path))[0]
cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__)
</code></pre>
| 11 | 2008-11-04T20:23:17Z | 900,775 | <p>I just create a simple "how to" where the program is in one module and the service is in another place, it uses py2exe to create the win32 service, which I believe is the best you can do for your users that don't want to mess with the python interpreter or other dependencies.</p>
<p>You can check my tutorial here: <a href="http://islascruz.org/html/index.php?gadget=StaticPage&action=Page&id=6" rel="nofollow">Create win32 services using Python and py2exe</a></p>
| 9 | 2009-05-23T03:20:19Z | [
"python",
"winapi",
"pywin32"
] |
Merging/adding lists in Python | 263,457 | <p>I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators.</p>
<p>Example - I have the following list:</p>
<pre><code>array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code></pre>
<p>I want to have</p>
<pre><code>result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9]
</code></pre>
<p>So far what I've come up with is:</p>
<pre><code>def add_list(array):
number_items = len(array[0])
result = [0] * number_items
for index in range(number_items):
for line in array:
result[index] += line[index]
return result
</code></pre>
<p>But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?</p>
| 33 | 2008-11-04T21:06:36Z | 263,465 | <pre><code>[sum(a) for a in zip(*array)]
</code></pre>
| 68 | 2008-11-04T21:16:39Z | [
"python",
"list"
] |
Merging/adding lists in Python | 263,457 | <p>I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators.</p>
<p>Example - I have the following list:</p>
<pre><code>array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code></pre>
<p>I want to have</p>
<pre><code>result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9]
</code></pre>
<p>So far what I've come up with is:</p>
<pre><code>def add_list(array):
number_items = len(array[0])
result = [0] * number_items
for index in range(number_items):
for line in array:
result[index] += line[index]
return result
</code></pre>
<p>But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?</p>
| 33 | 2008-11-04T21:06:36Z | 263,523 | <p>[sum(value) for value in zip(*array)] is pretty standard.</p>
<p>This might help you understand it:</p>
<pre><code>In [1]: array=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In [2]: array
Out[2]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In [3]: *array
------------------------------------------------------------
File "<ipython console>", line 1
*array
^
<type 'exceptions.SyntaxError'>: invalid syntax
</code></pre>
<p><em>The unary star is not an operator by itself. It unwraps array elements into arguments into function calls.</em></p>
<pre><code>In [4]: zip(*array)
Out[4]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
</code></pre>
<p><em>zip() is a built-in function</em></p>
<pre><code>In [5]: zip(*array)[0]
Out[5]: (1, 4, 7)
</code></pre>
<p><em>each element for the list returned by zip is a set of numbers you want.</em></p>
<pre><code>In [6]: sum(zip(*array)[0])
Out[6]: 12
In [7]: [sum(values) for values in zip(*array)]
Out[7]: [12, 15, 18]
</code></pre>
| 62 | 2008-11-04T21:33:47Z | [
"python",
"list"
] |
Merging/adding lists in Python | 263,457 | <p>I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators.</p>
<p>Example - I have the following list:</p>
<pre><code>array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code></pre>
<p>I want to have</p>
<pre><code>result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9]
</code></pre>
<p>So far what I've come up with is:</p>
<pre><code>def add_list(array):
number_items = len(array[0])
result = [0] * number_items
for index in range(number_items):
for line in array:
result[index] += line[index]
return result
</code></pre>
<p>But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?</p>
| 33 | 2008-11-04T21:06:36Z | 265,472 | <p>If you're doing a lot of this kind of thing, you want to learn about <a href="http://scipy.org/"><code>scipy</code>.</a></p>
<pre><code>>>> import scipy
>>> sum(scipy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
array([12, 15, 18])
</code></pre>
<p>All array sizes are checked for you automatically. The sum is done in pure C, so it's very fast. <code>scipy</code> arrays are also very memory efficient.</p>
<p>The drawback is you're dependent on a fairly complex third-party module. But that's a very good tradeoff for many purposes.</p>
| 8 | 2008-11-05T15:24:08Z | [
"python",
"list"
] |
Merging/adding lists in Python | 263,457 | <p>I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators.</p>
<p>Example - I have the following list:</p>
<pre><code>array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code></pre>
<p>I want to have</p>
<pre><code>result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9]
</code></pre>
<p>So far what I've come up with is:</p>
<pre><code>def add_list(array):
number_items = len(array[0])
result = [0] * number_items
for index in range(number_items):
for line in array:
result[index] += line[index]
return result
</code></pre>
<p>But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?</p>
| 33 | 2008-11-04T21:06:36Z | 265,495 | <p>An alternative way:</p>
<pre><code>map(sum, zip(*array))
</code></pre>
| 13 | 2008-11-05T15:31:04Z | [
"python",
"list"
] |
Merging/adding lists in Python | 263,457 | <p>I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators.</p>
<p>Example - I have the following list:</p>
<pre><code>array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code></pre>
<p>I want to have</p>
<pre><code>result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9]
</code></pre>
<p>So far what I've come up with is:</p>
<pre><code>def add_list(array):
number_items = len(array[0])
result = [0] * number_items
for index in range(number_items):
for line in array:
result[index] += line[index]
return result
</code></pre>
<p>But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?</p>
| 33 | 2008-11-04T21:06:36Z | 5,113,719 | <p>Agree with fivebells, but you could also use Numpy, which is a smaller (quicker import) and more generic implementation of array-like stuff. (actually, it is a dependency of scipy). These are great tools which, as have been said, are a 'must use' if you deal with this kind of manipulations.</p>
| 3 | 2011-02-25T04:45:31Z | [
"python",
"list"
] |
Merging/adding lists in Python | 263,457 | <p>I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators.</p>
<p>Example - I have the following list:</p>
<pre><code>array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code></pre>
<p>I want to have</p>
<pre><code>result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9]
</code></pre>
<p>So far what I've come up with is:</p>
<pre><code>def add_list(array):
number_items = len(array[0])
result = [0] * number_items
for index in range(number_items):
for line in array:
result[index] += line[index]
return result
</code></pre>
<p>But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?</p>
| 33 | 2008-11-04T21:06:36Z | 13,240,341 | <p>Late to the game, and it's not as good of an answer as some of the others, but I thought it was kind of cute:</p>
<pre><code>map(lambda *x:sum(x),*array)
</code></pre>
<p>it's too bad that <code>sum(1,2,3)</code> doesn't work. If it did, we could eliminate the silly <code>lambda</code> in there, but I suppose that would make it difficult to discern which (if any) of the elements is the "start" of the sum. You'd have to change that to a keyword only arguement which would break a lot of scripts ... Oh well. I guess we'll just live with <code>lambda</code>.</p>
| 2 | 2012-11-05T21:04:10Z | [
"python",
"list"
] |
Merging/adding lists in Python | 263,457 | <p>I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators.</p>
<p>Example - I have the following list:</p>
<pre><code>array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code></pre>
<p>I want to have</p>
<pre><code>result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9]
</code></pre>
<p>So far what I've come up with is:</p>
<pre><code>def add_list(array):
number_items = len(array[0])
result = [0] * number_items
for index in range(number_items):
for line in array:
result[index] += line[index]
return result
</code></pre>
<p>But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?</p>
| 33 | 2008-11-04T21:06:36Z | 27,910,105 | <p>It's not concise but it does work for adding lists of any size i.e. the list lengths do not match.</p>
<pre><code>def add_vectors(v1, v2):
"""
takes two lists of ints of any size and returns a third list
equal to the sum of their elements.
"""
vsum = []
v1len = len(v1)
v2len = len(v2)
offset = abs(v1len - v2len)
index = 0
if v1len > v2len:
llist = v1
slist = v2
elif v1len == v2len:
llist = v1
slist = v2
else:
llist = v2
slist = v1
while offset > 0:
#print 'llist is',llist,'slist is',slist,'appending 0 to',slist
slist.append(0)
offset -= 1
for v in llist:
vsum.append(v + slist[index])
index += 1
return vsum
print add_vectors([], [])
print add_vectors([1,2,3], [1,2,3])
print add_vectors([1,2,3], [1,2])
print add_vectors([1,2], [1,2,3])
</code></pre>
| 0 | 2015-01-12T20:21:00Z | [
"python",
"list"
] |
Merging/adding lists in Python | 263,457 | <p>I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators.</p>
<p>Example - I have the following list:</p>
<pre><code>array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code></pre>
<p>I want to have</p>
<pre><code>result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9]
</code></pre>
<p>So far what I've come up with is:</p>
<pre><code>def add_list(array):
number_items = len(array[0])
result = [0] * number_items
for index in range(number_items):
for line in array:
result[index] += line[index]
return result
</code></pre>
<p>But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?</p>
| 33 | 2008-11-04T21:06:36Z | 29,433,541 | <blockquote>
<p>[sum(a) for a in zip(*array)]</p>
</blockquote>
<p>I like that. I needed something related for interleaving objects in to a list of items, came up with something similar but more concise for even length lists:</p>
<pre><code>sum(zip(*array),())
</code></pre>
<p>for example, interleaving two lists:</p>
<pre><code>a = [1,2,3]
b = ['a','b','c']
sum(zip(a,b),())
(1, 'a', 2, 'b', 3, 'c')
</code></pre>
| 0 | 2015-04-03T13:55:00Z | [
"python",
"list"
] |
Merging/adding lists in Python | 263,457 | <p>I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators.</p>
<p>Example - I have the following list:</p>
<pre><code>array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code></pre>
<p>I want to have</p>
<pre><code>result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9]
</code></pre>
<p>So far what I've come up with is:</p>
<pre><code>def add_list(array):
number_items = len(array[0])
result = [0] * number_items
for index in range(number_items):
for line in array:
result[index] += line[index]
return result
</code></pre>
<p>But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?</p>
| 33 | 2008-11-04T21:06:36Z | 29,439,639 | <p>You can simply do this:</p>
<pre><code>print [sum(x) for x in zip(*array)]
</code></pre>
<p>If you wish to iterate through lists in this fashion, you can use <code>chain</code> of the <code>itertools</code> module:</p>
<pre><code>from itertools import chain
for x in array.chain.from_iterable(zip(*array)):
print x
# prints 1, 4, 7, 2, 5, 8, ...
</code></pre>
| 0 | 2015-04-03T21:02:37Z | [
"python",
"list"
] |
We have a graphical designer, now they want a text based designer. Suggestions? | 263,550 | <p>I'm sorry I could not think of a better title.</p>
<p>The problem is the following:</p>
<p>For our customer we have created (as part of a larger application) a
graphical designer which they can use to build "scenario's".</p>
<p>These scenario's consist of "Composites" which in turn consist
of "Commands". These command objects all derive from CommandBase and
implement an interface called ICompilable.</p>
<p>The scenario class also implements ICompilable. When Compile() is called
on a command an array of bytes is returned which can then be send to the device
for which they are intended (can't disclose to much info about that hardware, sorry)</p>
<p>Just to give you an idea:</p>
<pre><code>var scenario = new Scenario();
scenario.Add(new DelayCommand(1));
scenario.Add(new CountWithValueCommand(1,ActionEnum.Add,1));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new WaitCommand(3));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new SkipIfCommand(1,OperatorEnum.SmallerThan,10));
scenario.Add(new JumpCommand(2));
byte[] compiledData = scenario.Compile();
</code></pre>
<p>The graphical designer abstracts all this from the user and allows
him (or her) to simply drag en drop composites onto the designer surface.
(Composites can group commands so we can provide building blocks for returning tasks)</p>
<p>Recently our customer came to us and said, "well the designer is really cool,
but we have some people who would rather have some kind of programming language,
just something simple."</p>
<p>(Simple to them of course)</p>
<p>I would very much like to provide them with a simple language,
that can call various commmands and also replace SkipIfCommand with
a nicer structure, etc...</p>
<p>I have no idea where to start or what my options are (without breaking what we have)</p>
<p>I have heard about people embedding languages such as Python,
people writing their own language an parsers, etc...</p>
<p>Any suggestions?</p>
<p>PS: Users only work with composites, never with commands.
Composites are loaded dynamically at runtime (along with their graphical designer)
and may be provided by third parties in seperate assemblies.</p>
| 4 | 2008-11-04T21:39:36Z | 263,583 | <p>From what i think i've understood you have two options</p>
<p>you could either use an XML style "markup" to let them define entities and their groupings, but that may not be best.</p>
<p>Your alternatives are yes, yoou could embedd a language, but do you really need to, wouldnt that be overkill, and how can you control it?</p>
<p>If you only need really simple syntax then perhaps write your own language. Its actually not that hard to create a simple interpreter, as long as you have a strict, unambiguous language. Have a look for some examples of compilers in whatever youre using, c#?</p>
<p>I wrote a very simple interperter in java at uni, it wasnt as hard as you'd think.</p>
| 4 | 2008-11-04T21:47:19Z | [
"c#",
"python",
"scripting",
"parsing",
"embedding"
] |
We have a graphical designer, now they want a text based designer. Suggestions? | 263,550 | <p>I'm sorry I could not think of a better title.</p>
<p>The problem is the following:</p>
<p>For our customer we have created (as part of a larger application) a
graphical designer which they can use to build "scenario's".</p>
<p>These scenario's consist of "Composites" which in turn consist
of "Commands". These command objects all derive from CommandBase and
implement an interface called ICompilable.</p>
<p>The scenario class also implements ICompilable. When Compile() is called
on a command an array of bytes is returned which can then be send to the device
for which they are intended (can't disclose to much info about that hardware, sorry)</p>
<p>Just to give you an idea:</p>
<pre><code>var scenario = new Scenario();
scenario.Add(new DelayCommand(1));
scenario.Add(new CountWithValueCommand(1,ActionEnum.Add,1));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new WaitCommand(3));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new SkipIfCommand(1,OperatorEnum.SmallerThan,10));
scenario.Add(new JumpCommand(2));
byte[] compiledData = scenario.Compile();
</code></pre>
<p>The graphical designer abstracts all this from the user and allows
him (or her) to simply drag en drop composites onto the designer surface.
(Composites can group commands so we can provide building blocks for returning tasks)</p>
<p>Recently our customer came to us and said, "well the designer is really cool,
but we have some people who would rather have some kind of programming language,
just something simple."</p>
<p>(Simple to them of course)</p>
<p>I would very much like to provide them with a simple language,
that can call various commmands and also replace SkipIfCommand with
a nicer structure, etc...</p>
<p>I have no idea where to start or what my options are (without breaking what we have)</p>
<p>I have heard about people embedding languages such as Python,
people writing their own language an parsers, etc...</p>
<p>Any suggestions?</p>
<p>PS: Users only work with composites, never with commands.
Composites are loaded dynamically at runtime (along with their graphical designer)
and may be provided by third parties in seperate assemblies.</p>
| 4 | 2008-11-04T21:39:36Z | 263,664 | <p>This looks like a perfect scenario for a simple DSL. See <a href="http://msdn.microsoft.com/en-us/library/bb126235(VS.80).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb126235(VS.80).aspx</a> for some information.</p>
<p>You could also use a scripting language such as lua.Net. </p>
| 2 | 2008-11-04T22:08:12Z | [
"c#",
"python",
"scripting",
"parsing",
"embedding"
] |
We have a graphical designer, now they want a text based designer. Suggestions? | 263,550 | <p>I'm sorry I could not think of a better title.</p>
<p>The problem is the following:</p>
<p>For our customer we have created (as part of a larger application) a
graphical designer which they can use to build "scenario's".</p>
<p>These scenario's consist of "Composites" which in turn consist
of "Commands". These command objects all derive from CommandBase and
implement an interface called ICompilable.</p>
<p>The scenario class also implements ICompilable. When Compile() is called
on a command an array of bytes is returned which can then be send to the device
for which they are intended (can't disclose to much info about that hardware, sorry)</p>
<p>Just to give you an idea:</p>
<pre><code>var scenario = new Scenario();
scenario.Add(new DelayCommand(1));
scenario.Add(new CountWithValueCommand(1,ActionEnum.Add,1));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new WaitCommand(3));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new SkipIfCommand(1,OperatorEnum.SmallerThan,10));
scenario.Add(new JumpCommand(2));
byte[] compiledData = scenario.Compile();
</code></pre>
<p>The graphical designer abstracts all this from the user and allows
him (or her) to simply drag en drop composites onto the designer surface.
(Composites can group commands so we can provide building blocks for returning tasks)</p>
<p>Recently our customer came to us and said, "well the designer is really cool,
but we have some people who would rather have some kind of programming language,
just something simple."</p>
<p>(Simple to them of course)</p>
<p>I would very much like to provide them with a simple language,
that can call various commmands and also replace SkipIfCommand with
a nicer structure, etc...</p>
<p>I have no idea where to start or what my options are (without breaking what we have)</p>
<p>I have heard about people embedding languages such as Python,
people writing their own language an parsers, etc...</p>
<p>Any suggestions?</p>
<p>PS: Users only work with composites, never with commands.
Composites are loaded dynamically at runtime (along with their graphical designer)
and may be provided by third parties in seperate assemblies.</p>
| 4 | 2008-11-04T21:39:36Z | 263,675 | <p>If you really just want a dirt simple language, you want a 'recursive descent parser'.</p>
<p>For example, a language like this:</p>
<pre><code>SCENARIO MyScenario
DELAY 1
COUNT 1 ADD 1
DIRECT_POWER 23, False, 150
WAIT 3
...
END_SCENARIO
</code></pre>
<p>You might have a grammar like:</p>
<pre><code>scenario :: 'SCENARIO' label newline _cmds END_SCENARIO
cmds:: _delay or _count or _direct_power or...
delay:: 'DELAY' number
</code></pre>
<p>Which gives code like:</p>
<pre><code>def scenario():
match_word('SCENARIO')
scenario_name = match_label()
emit('var scenario = new Scenario();')
cmds()
match_word('END_SCENARIO')
emit('byte[] ' + scenario_name + ' = scenario.Compile();')
def delay():
match_word('DELAY')
length = match_number()
emit('scenario.Add(new DelayCommand('+ length +'))')
def cmds():
word = peek_next_word()
if word == 'DELAY':
delay()
elif ...
</code></pre>
| 2 | 2008-11-04T22:11:58Z | [
"c#",
"python",
"scripting",
"parsing",
"embedding"
] |
We have a graphical designer, now they want a text based designer. Suggestions? | 263,550 | <p>I'm sorry I could not think of a better title.</p>
<p>The problem is the following:</p>
<p>For our customer we have created (as part of a larger application) a
graphical designer which they can use to build "scenario's".</p>
<p>These scenario's consist of "Composites" which in turn consist
of "Commands". These command objects all derive from CommandBase and
implement an interface called ICompilable.</p>
<p>The scenario class also implements ICompilable. When Compile() is called
on a command an array of bytes is returned which can then be send to the device
for which they are intended (can't disclose to much info about that hardware, sorry)</p>
<p>Just to give you an idea:</p>
<pre><code>var scenario = new Scenario();
scenario.Add(new DelayCommand(1));
scenario.Add(new CountWithValueCommand(1,ActionEnum.Add,1));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new WaitCommand(3));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new SkipIfCommand(1,OperatorEnum.SmallerThan,10));
scenario.Add(new JumpCommand(2));
byte[] compiledData = scenario.Compile();
</code></pre>
<p>The graphical designer abstracts all this from the user and allows
him (or her) to simply drag en drop composites onto the designer surface.
(Composites can group commands so we can provide building blocks for returning tasks)</p>
<p>Recently our customer came to us and said, "well the designer is really cool,
but we have some people who would rather have some kind of programming language,
just something simple."</p>
<p>(Simple to them of course)</p>
<p>I would very much like to provide them with a simple language,
that can call various commmands and also replace SkipIfCommand with
a nicer structure, etc...</p>
<p>I have no idea where to start or what my options are (without breaking what we have)</p>
<p>I have heard about people embedding languages such as Python,
people writing their own language an parsers, etc...</p>
<p>Any suggestions?</p>
<p>PS: Users only work with composites, never with commands.
Composites are loaded dynamically at runtime (along with their graphical designer)
and may be provided by third parties in seperate assemblies.</p>
| 4 | 2008-11-04T21:39:36Z | 263,727 | <p>Here's a Pythonic solution for building a DSL that you can use to compile and create byte code arrays.</p>
<ol>
<li><p>Write a simple module that makes your C# structures available to Python. The goal is to define each C# class that users are allowed to work with (Composites or Commands or whatever) as a Python class.</p>
<p>Usually, this involves implementing a minimal set of methods with different conversions from C# types to native Python types and vice versa.</p></li>
<li><p>Write some nice demos showing how to use these Python class definitions to create their scripts. You should be able to create things like this in Python.</p>
<pre><code>import * from someInterfaceModule
scenario= Scenario(
Delay(1),
Repeat( Range(10),
DirectPower( 23, False, 150),
Wait(3),
DirectPower( 23, False, 150)
)
)
scenario.compile()
</code></pre></li>
</ol>
<p>These are relatively simple classes to define. Each class here be reasonably easy to implement as Python modules that directly call your base C# modules.</p>
<p>The syntax is pure Python with no additional parsing or lexical scanning required.</p>
| 1 | 2008-11-04T22:31:45Z | [
"c#",
"python",
"scripting",
"parsing",
"embedding"
] |
We have a graphical designer, now they want a text based designer. Suggestions? | 263,550 | <p>I'm sorry I could not think of a better title.</p>
<p>The problem is the following:</p>
<p>For our customer we have created (as part of a larger application) a
graphical designer which they can use to build "scenario's".</p>
<p>These scenario's consist of "Composites" which in turn consist
of "Commands". These command objects all derive from CommandBase and
implement an interface called ICompilable.</p>
<p>The scenario class also implements ICompilable. When Compile() is called
on a command an array of bytes is returned which can then be send to the device
for which they are intended (can't disclose to much info about that hardware, sorry)</p>
<p>Just to give you an idea:</p>
<pre><code>var scenario = new Scenario();
scenario.Add(new DelayCommand(1));
scenario.Add(new CountWithValueCommand(1,ActionEnum.Add,1));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new WaitCommand(3));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new SkipIfCommand(1,OperatorEnum.SmallerThan,10));
scenario.Add(new JumpCommand(2));
byte[] compiledData = scenario.Compile();
</code></pre>
<p>The graphical designer abstracts all this from the user and allows
him (or her) to simply drag en drop composites onto the designer surface.
(Composites can group commands so we can provide building blocks for returning tasks)</p>
<p>Recently our customer came to us and said, "well the designer is really cool,
but we have some people who would rather have some kind of programming language,
just something simple."</p>
<p>(Simple to them of course)</p>
<p>I would very much like to provide them with a simple language,
that can call various commmands and also replace SkipIfCommand with
a nicer structure, etc...</p>
<p>I have no idea where to start or what my options are (without breaking what we have)</p>
<p>I have heard about people embedding languages such as Python,
people writing their own language an parsers, etc...</p>
<p>Any suggestions?</p>
<p>PS: Users only work with composites, never with commands.
Composites are loaded dynamically at runtime (along with their graphical designer)
and may be provided by third parties in seperate assemblies.</p>
| 4 | 2008-11-04T21:39:36Z | 263,742 | <p>To add to S.Lott's comment, here's how you <a href="http://www.redmountainsw.com/wordpress/archives/embedding-ironpython-c-calling-python-script" rel="nofollow">eval a Python script from C# </a></p>
| 1 | 2008-11-04T22:36:41Z | [
"c#",
"python",
"scripting",
"parsing",
"embedding"
] |
We have a graphical designer, now they want a text based designer. Suggestions? | 263,550 | <p>I'm sorry I could not think of a better title.</p>
<p>The problem is the following:</p>
<p>For our customer we have created (as part of a larger application) a
graphical designer which they can use to build "scenario's".</p>
<p>These scenario's consist of "Composites" which in turn consist
of "Commands". These command objects all derive from CommandBase and
implement an interface called ICompilable.</p>
<p>The scenario class also implements ICompilable. When Compile() is called
on a command an array of bytes is returned which can then be send to the device
for which they are intended (can't disclose to much info about that hardware, sorry)</p>
<p>Just to give you an idea:</p>
<pre><code>var scenario = new Scenario();
scenario.Add(new DelayCommand(1));
scenario.Add(new CountWithValueCommand(1,ActionEnum.Add,1));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new WaitCommand(3));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new SkipIfCommand(1,OperatorEnum.SmallerThan,10));
scenario.Add(new JumpCommand(2));
byte[] compiledData = scenario.Compile();
</code></pre>
<p>The graphical designer abstracts all this from the user and allows
him (or her) to simply drag en drop composites onto the designer surface.
(Composites can group commands so we can provide building blocks for returning tasks)</p>
<p>Recently our customer came to us and said, "well the designer is really cool,
but we have some people who would rather have some kind of programming language,
just something simple."</p>
<p>(Simple to them of course)</p>
<p>I would very much like to provide them with a simple language,
that can call various commmands and also replace SkipIfCommand with
a nicer structure, etc...</p>
<p>I have no idea where to start or what my options are (without breaking what we have)</p>
<p>I have heard about people embedding languages such as Python,
people writing their own language an parsers, etc...</p>
<p>Any suggestions?</p>
<p>PS: Users only work with composites, never with commands.
Composites are loaded dynamically at runtime (along with their graphical designer)
and may be provided by third parties in seperate assemblies.</p>
| 4 | 2008-11-04T21:39:36Z | 263,931 | <p>While it might be great fun to create this mini-language and code it all up, the real questions you need to ask are:</p>
<ol>
<li>What is the business case for adding this feature / facility?</li>
<li>Who is going to pay for this feature?</li>
<li>Who is going to "sign off" on this feature if you build it?</li>
</ol>
<p>"Really neat" features have a way of getting built when the reality might indicate the true answer to such a request is "no".</p>
<p>See if you have a stakeholder willing to sponsor this before proceeding. Then check with the end users to see what they really want before committing to the project.</p>
<p>Cheers,</p>
<p>-R</p>
| 0 | 2008-11-04T23:57:34Z | [
"c#",
"python",
"scripting",
"parsing",
"embedding"
] |
What is a Ruby equivalent for Python's "zip" builtin? | 263,623 | <p>Is there any Ruby equivalent for Python's builtin <code>zip</code> function? If not, what is a concise way of doing the same thing?</p>
<p>A bit of context: this came up when I was trying to find a clean way of doing a check involving two arrays. If I had <code>zip</code>, I could have written something like:</p>
<pre><code>zip(a, b).all? {|pair| pair[0] === pair[1]}
</code></pre>
<p>I'd also accept a clean way of doing this without anything resembling <code>zip</code> (where "clean" means "without an explicit loop").</p>
| 14 | 2008-11-04T21:58:29Z | 263,652 | <p>Ruby has a zip function:</p>
<pre><code>[1,2].zip([3,4]) => [[1,3],[2,4]]
</code></pre>
<p>so your code example is actually:</p>
<pre><code>a.zip(b).all? {|pair| pair[0] === pair[1]}
</code></pre>
<p>or perhaps more succinctly:</p>
<pre><code>a.zip(b).all? {|a,b| a === b }
</code></pre>
| 21 | 2008-11-04T22:05:46Z | [
"python",
"ruby",
"translation"
] |
What is a Ruby equivalent for Python's "zip" builtin? | 263,623 | <p>Is there any Ruby equivalent for Python's builtin <code>zip</code> function? If not, what is a concise way of doing the same thing?</p>
<p>A bit of context: this came up when I was trying to find a clean way of doing a check involving two arrays. If I had <code>zip</code>, I could have written something like:</p>
<pre><code>zip(a, b).all? {|pair| pair[0] === pair[1]}
</code></pre>
<p>I'd also accept a clean way of doing this without anything resembling <code>zip</code> (where "clean" means "without an explicit loop").</p>
| 14 | 2008-11-04T21:58:29Z | 263,670 | <p>Could you not do:</p>
<pre><code>a.eql?(b)
</code></pre>
<p>Edited to add an example:</p>
<pre><code>a = %w[a b c]
b = %w[1 2 3]
c = ['a', 'b', 'c']
a.eql?(b) # => false
a.eql?(c) # => true
a.eql?(c.reverse) # => false
</code></pre>
| 0 | 2008-11-04T22:09:07Z | [
"python",
"ruby",
"translation"
] |
What is a Ruby equivalent for Python's "zip" builtin? | 263,623 | <p>Is there any Ruby equivalent for Python's builtin <code>zip</code> function? If not, what is a concise way of doing the same thing?</p>
<p>A bit of context: this came up when I was trying to find a clean way of doing a check involving two arrays. If I had <code>zip</code>, I could have written something like:</p>
<pre><code>zip(a, b).all? {|pair| pair[0] === pair[1]}
</code></pre>
<p>I'd also accept a clean way of doing this without anything resembling <code>zip</code> (where "clean" means "without an explicit loop").</p>
| 14 | 2008-11-04T21:58:29Z | 266,848 | <p>This is from the ruby spec:</p>
<pre><code>it "returns true if other has the same length and each pair of corresponding elements are eql" do
a = [1, 2, 3, 4]
b = [1, 2, 3, 4]
a.should eql(b)
[].should eql([])
end
</code></pre>
<p>So you should it should work for the example you mentioned.</p>
<p>If you're not using integers, but custom objects I <em>think</em> you need to override eql?.</p>
<p>The spec for this method is here:</p>
<p><a href="http://github.com/rubyspec/rubyspec/tree/master/1.8/core/array/eql_spec.rb" rel="nofollow">http://github.com/rubyspec/rubyspec/tree/master/1.8/core/array/eql_spec.rb</a></p>
| -2 | 2008-11-05T21:49:58Z | [
"python",
"ruby",
"translation"
] |
How can I ask for root password but perform the action at a later time? | 263,773 | <p>I have a python script that I would like to add a "Shutdown when done" feature to.</p>
<p>I know I can use gksudo (when the user clicks on "shutdown when done") to ask the user for root privileges but how can I use those privileges at a later time (when the script is actually finished).</p>
<p>I have thought about chmod u+s on the shutdown command so I don't need a password but I really don't want to do that.</p>
<p>Any ideas how I can achieve this?</p>
<p>Thanks in advance,
Ashy.</p>
| 7 | 2008-11-04T22:47:39Z | 263,804 | <p>gksudo should have a timeout, I believe it's from the time you last executed a gksudo command.</p>
<p>So I think I'd just throw out a "gksudo echo meh" or something every minute. Should reset the timer and keep you active until you reboot.</p>
| 3 | 2008-11-04T23:02:05Z | [
"python",
"linux",
"ubuntu"
] |
How can I ask for root password but perform the action at a later time? | 263,773 | <p>I have a python script that I would like to add a "Shutdown when done" feature to.</p>
<p>I know I can use gksudo (when the user clicks on "shutdown when done") to ask the user for root privileges but how can I use those privileges at a later time (when the script is actually finished).</p>
<p>I have thought about chmod u+s on the shutdown command so I don't need a password but I really don't want to do that.</p>
<p>Any ideas how I can achieve this?</p>
<p>Thanks in advance,
Ashy.</p>
| 7 | 2008-11-04T22:47:39Z | 263,851 | <p>Escalate priority, spawn (<code>fork (2)</code>) a separate process that will <code>wait (2)</code>, and drop priority in the main process.</p>
| 1 | 2008-11-04T23:18:05Z | [
"python",
"linux",
"ubuntu"
] |
How can I ask for root password but perform the action at a later time? | 263,773 | <p>I have a python script that I would like to add a "Shutdown when done" feature to.</p>
<p>I know I can use gksudo (when the user clicks on "shutdown when done") to ask the user for root privileges but how can I use those privileges at a later time (when the script is actually finished).</p>
<p>I have thought about chmod u+s on the shutdown command so I don't need a password but I really don't want to do that.</p>
<p>Any ideas how I can achieve this?</p>
<p>Thanks in advance,
Ashy.</p>
| 7 | 2008-11-04T22:47:39Z | 263,859 | <p>Instead of <code>chmod u+s</code>ing the shutdown command, allowing passwordless sudo access to that command would be better..</p>
<p>As for allowing shutdown at the end of the script, I suppose you could run the entire script with sudo, then drop privileges to the initial user at the start of the script?</p>
| 4 | 2008-11-04T23:21:50Z | [
"python",
"linux",
"ubuntu"
] |
launching vs2008 build from python | 263,820 | <p>The first batch file launches a command prompt, i need the second command to be in the ccontext of the first. how can I do this in python?</p>
<p>As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes <code>devenv</code> without the necessary context.</p>
<pre><code>os.system(r'%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86')
os.system(r'devenv asdf.sln /rebuild Debug /Out last-build.txt')
</code></pre>
<p>think of it as in i'm in bash, and i need to execute a command in a perl context, so i type <code>perl -c 'asdf'</code>. executing perl and asdf back to back won't work, i need to get the <code>devenv</code> inside of the perl context.</p>
| 1 | 2008-11-04T23:08:03Z | 263,856 | <p>You could append the devenv command onto the end of the original batch file like so:</p>
<pre><code>'%comspec% /k "...vcvarsall.bat" x86 && devenv asdf.sln /rebuild ...'
</code></pre>
<p>(obviously I have shortened the commands for simplicity's sake)</p>
| 2 | 2008-11-04T23:21:24Z | [
"python",
"windows",
"visual-studio-2008",
"build-automation"
] |
launching vs2008 build from python | 263,820 | <p>The first batch file launches a command prompt, i need the second command to be in the ccontext of the first. how can I do this in python?</p>
<p>As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes <code>devenv</code> without the necessary context.</p>
<pre><code>os.system(r'%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86')
os.system(r'devenv asdf.sln /rebuild Debug /Out last-build.txt')
</code></pre>
<p>think of it as in i'm in bash, and i need to execute a command in a perl context, so i type <code>perl -c 'asdf'</code>. executing perl and asdf back to back won't work, i need to get the <code>devenv</code> inside of the perl context.</p>
| 1 | 2008-11-04T23:08:03Z | 263,881 | <p>I these situations I use script that does it all. That way you can chain as much as you want. Sometimes I will generate the script on the fly.</p>
<pre><code>compileit.cmd
call C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat
devenv $1.sln /rebuild Debug /Out last-build.txt
</code></pre>
| 2 | 2008-11-04T23:29:38Z | [
"python",
"windows",
"visual-studio-2008",
"build-automation"
] |
launching vs2008 build from python | 263,820 | <p>The first batch file launches a command prompt, i need the second command to be in the ccontext of the first. how can I do this in python?</p>
<p>As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes <code>devenv</code> without the necessary context.</p>
<pre><code>os.system(r'%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86')
os.system(r'devenv asdf.sln /rebuild Debug /Out last-build.txt')
</code></pre>
<p>think of it as in i'm in bash, and i need to execute a command in a perl context, so i type <code>perl -c 'asdf'</code>. executing perl and asdf back to back won't work, i need to get the <code>devenv</code> inside of the perl context.</p>
| 1 | 2008-11-04T23:08:03Z | 288,734 | <p>I run my Python script from a batch file that sets the variables :-)</p>
<pre><code>call ...\vcvarsall.bat
c:\python26\python.exe myscript.py
</code></pre>
<p>But Brett's solution sounds better.</p>
| 2 | 2008-11-13T23:24:48Z | [
"python",
"windows",
"visual-studio-2008",
"build-automation"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.