title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
kill subprocess when python process is killed?
1,603,658
<p>I am writing a python program that lauches a subprocess (using Popen). I am reading stdout of the subprocess, doing some filtering, and writing to stdout of main process.</p> <p>When I kill the main process (cntl-C) the subprocess keeps running. How do I kill the subprocess too? The subprocess is likey to run a long time.</p> <p>Context: I'm launching only one subprocess at a time, I'm filtering its stdout. The user might decide to interrupt to try something else.</p> <p>I'm new to python and I'm using windows, so please be gentle.</p>
7
2009-10-21T21:08:21Z
1,603,828
<p>subprocess.Popen objects come with a kill and a terminate method (differs in which signal you send to the process).</p> <p>signal.signal allows you install signal handlers, in which you can call the child's kill method.</p>
0
2009-10-21T21:40:35Z
[ "python", "windows", "process" ]
kill subprocess when python process is killed?
1,603,658
<p>I am writing a python program that lauches a subprocess (using Popen). I am reading stdout of the subprocess, doing some filtering, and writing to stdout of main process.</p> <p>When I kill the main process (cntl-C) the subprocess keeps running. How do I kill the subprocess too? The subprocess is likey to run a long time.</p> <p>Context: I'm launching only one subprocess at a time, I'm filtering its stdout. The user might decide to interrupt to try something else.</p> <p>I'm new to python and I'm using windows, so please be gentle.</p>
7
2009-10-21T21:08:21Z
28,664,402
<p>You can use python <code>atexit</code> module.</p> <p>For example:</p> <pre><code>import atexit def killSubprocess(): mySubprocess.kill() atexit.register(killSubprocess) </code></pre>
0
2015-02-22T23:00:17Z
[ "python", "windows", "process" ]
CherryPy, load image from matplotlib, or in general
1,603,669
<p>I am not sure what I am doing wrong, It would be great if you could point me toward what to read. I have taken the first CherryPy tutorial "hello world" added a little matplotlib plot. Question 1: how do I know where the file will be saved? It happens to be where I am running the file. Question 2: I don't seem to be get the image to open/view in my browser. When I view source in the browser everything looks right but no luck, even when I am including the full image path. I think my problem is with the path but not sure the mechanics of what is happening</p> <p>thanks for the help Vincent</p> <pre><code>import cherrypy import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt class HelloWorld: def index(self): fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1,2,3]) fig.savefig('test.png') return ''' &lt;img src="test.png" width="640" height="480" border="0" /&gt; ''' index.exposed = True import os.path tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf') if __name__ == '__main__': cherrypy.quickstart(HelloWorld(), config=tutconf) else: cherrypy.tree.mount(HelloWorld(), config=tutconf) </code></pre>
4
2009-10-21T21:10:33Z
1,604,037
<p>Below are some things that have worked for me, but before you proceed further I recommend that you read <a href="http://www.cherrypy.org/wiki/StaticContent">this page</a> about how to configure directories which contain static content.</p> <p><strong>Question 1: How do I know where the file will be saved?</strong><br /> If you dictate where the file should be saved, the process of finding it should become easier.<br /> For example, you could save image files to a subdirectory called "img" within your CherryPy application directory like this:</p> <pre><code>fig.savefig('img/test.png') # note: *no* forward slash before "img" </code></pre> <p>And then display like this:</p> <pre><code>return '&lt;img src="/img/test.png" /&gt;' # note: forward slash before "img" </code></pre> <p><strong>Question 2: I don't seem to be [able to] get the image to open/view in my browser.</strong><br /> Here is one way I've used to make static images available to a CherryPy application:</p> <pre><code>if __name__ == '__main__': import os.path currdir = os.path.dirname(os.path.abspath(__file__)) conf = {'/css/style.css':{'tools.staticfile.on':True, 'tools.staticfile.filename':os.path.join(currdir,'css','style.css')}, '/img':{'tools.staticdir.on':True, 'tools.staticdir.dir':os.path.join(currdir,'img')}} cherrypy.quickstart(root, "/", config=conf) </code></pre>
5
2009-10-21T22:33:32Z
[ "python", "matplotlib", "cherrypy" ]
Why is this simple python class not working?
1,603,696
<p>I'm trying to make a class that will get a list of numbers then print them out when I need. I need to be able to make 2 objects from the class to get two different lists. Here's what I have so far </p> <pre><code>class getlist: def newlist(self,*number): lst=[] self.number=number lst.append(number) def printlist(self): return lst </code></pre> <p>Sorry I'm not very clear, I'm a bit new to oop, can you please help me cos I don't know what I'm doing wrong. Thanks.</p>
2
2009-10-21T21:15:55Z
1,603,733
<p>In Python, when you are writing methods inside an object, you need to prefix all references to variables belonging to that object with self. - like so:</p> <pre><code>class getlist: def newlist(self,*number): self.lst=[] self.lst += number #I changed this to add all args to the list def printlist(self): return self.lst </code></pre> <p>The code you had before was creating and modifying a local variable called lst, so it would appear to "disappear" between calls.</p> <p>Also, it is usual to make a constructor, which has the special name <code>__init__</code> : </p> <pre><code>class getlist: #Init constructor def __init__(self,*number): self.lst=[] self.lst += number #I changed this to add all args to the list def printlist(self): return self.lst </code></pre> <p>Finally, use like so</p> <pre><code>&gt;&gt;&gt; newlist=getlist(1,2,3, [4,5]) &gt;&gt;&gt; newlist.printlist() [1, 2, 3, [4,5]] </code></pre>
7
2009-10-21T21:19:11Z
[ "python", "class", "list" ]
Why is this simple python class not working?
1,603,696
<p>I'm trying to make a class that will get a list of numbers then print them out when I need. I need to be able to make 2 objects from the class to get two different lists. Here's what I have so far </p> <pre><code>class getlist: def newlist(self,*number): lst=[] self.number=number lst.append(number) def printlist(self): return lst </code></pre> <p>Sorry I'm not very clear, I'm a bit new to oop, can you please help me cos I don't know what I'm doing wrong. Thanks.</p>
2
2009-10-21T21:15:55Z
1,603,741
<p>You should use "self.lst" instead of "lst". Without the "self", it's just internal variable to current method.</p>
3
2009-10-21T21:20:12Z
[ "python", "class", "list" ]
What is the right way to design an adventure game with PyGame?
1,603,928
<p>I have started development on a small 2d adventure side view game together with a couple of people. The game will consist of the regular elements: A room, a main character, an inventory, npcs, items and puzzles. We've chosen PyGame since we all are familiar with python from before. My question is quite theoretical, but how would we design this in a good way? Would every object on the screen talk to some main loop that blits everything to the screen? (Hope this question isn't too discussion-y) Thanks</p>
2
2009-10-21T22:04:28Z
1,604,115
<p>Python Adventure Writing System - <a href="http://home.fuse.net/wolfonenet/PAWS.htm" rel="nofollow">http://home.fuse.net/wolfonenet/PAWS.htm</a> - might be useful</p> <p><a href="http://proquestcombo.safaribooksonline.com/1592000770" rel="nofollow">http://proquestcombo.safaribooksonline.com/1592000770</a> may also be useful</p>
1
2009-10-21T22:55:23Z
[ "python", "design", "pygame" ]
How can I modify a Python traceback object when raising an exception?
1,603,940
<p>I'm working on a Python library used by third-party developers to write extensions for our core application.</p> <p>I'd like to know if it's possible to modify the traceback when raising exceptions, so the last stack frame is the call to the library function in the developer's code, rather than the line in the library that raised the exception. There are also a few frames at the bottom of the stack containing references to functions used when first loading the code that I'd ideally like to remove too.</p> <p>Thanks in advance for any advice!</p>
11
2009-10-21T22:08:06Z
1,603,972
<p>Take a look at what jinja2 does here:</p> <p><a href="https://github.com/mitsuhiko/jinja2/blob/5b498453b5898257b2287f14ef6c363799f1405a/jinja2/debug.py" rel="nofollow">https://github.com/mitsuhiko/jinja2/blob/5b498453b5898257b2287f14ef6c363799f1405a/jinja2/debug.py</a></p> <p>It's ugly, but it seems to do what you need done. I won't copy-paste the example here because it's long.</p>
6
2009-10-21T22:13:23Z
[ "python", "traceback" ]
How can I modify a Python traceback object when raising an exception?
1,603,940
<p>I'm working on a Python library used by third-party developers to write extensions for our core application.</p> <p>I'd like to know if it's possible to modify the traceback when raising exceptions, so the last stack frame is the call to the library function in the developer's code, rather than the line in the library that raised the exception. There are also a few frames at the bottom of the stack containing references to functions used when first loading the code that I'd ideally like to remove too.</p> <p>Thanks in advance for any advice!</p>
11
2009-10-21T22:08:06Z
1,843,184
<p>What about not changing the traceback? The two things you request can both be done more easily in a different way.</p> <ol> <li>If the exception from the library is caught in the developer's code and a new exception is raised instead, the original traceback will of course be tossed. This is how exceptions are generally handled... if you just allow the original exception to be raised but you munge it to remove all the "upper" frames, the actual exception won't make sense since the last line in the traceback would not itself be capable of raising the exception.</li> <li>To strip out the last few frames, you can request that your tracebacks be shortened... things like traceback.print_exception() take a "limit" parameter which you could use to skip the last few entries.</li> </ol> <p>That said, it should be quite possible to munge the tracebacks if you really need to... but where would you do it? If in some wrapper code at the very top level, then you could simply grab the traceback, take a slice to remove the parts you don't want, and then use functions in the "traceback" module to format/print as desired.</p>
1
2009-12-03T21:52:36Z
[ "python", "traceback" ]
How can I modify a Python traceback object when raising an exception?
1,603,940
<p>I'm working on a Python library used by third-party developers to write extensions for our core application.</p> <p>I'd like to know if it's possible to modify the traceback when raising exceptions, so the last stack frame is the call to the library function in the developer's code, rather than the line in the library that raised the exception. There are also a few frames at the bottom of the stack containing references to functions used when first loading the code that I'd ideally like to remove too.</p> <p>Thanks in advance for any advice!</p>
11
2009-10-21T22:08:06Z
12,381,678
<p>You might also be interested in <a href="http://www.python.org/dev/peps/pep-3134/" rel="nofollow">PEP-3134</a>, which is implemented in python 3 and allows you to tack one exception/traceback onto an upstream exception.</p> <p>This isn't quite the same thing as modifying the traceback, but it would probably be the ideal way to convey the "short version" to library users while still having the "long version" available.</p>
1
2012-09-12T05:24:01Z
[ "python", "traceback" ]
How can I modify a Python traceback object when raising an exception?
1,603,940
<p>I'm working on a Python library used by third-party developers to write extensions for our core application.</p> <p>I'd like to know if it's possible to modify the traceback when raising exceptions, so the last stack frame is the call to the library function in the developer's code, rather than the line in the library that raised the exception. There are also a few frames at the bottom of the stack containing references to functions used when first loading the code that I'd ideally like to remove too.</p> <p>Thanks in advance for any advice!</p>
11
2009-10-21T22:08:06Z
13,898,994
<p>You can remove the top of the traceback easily with by raising with the tb_next element of the traceback:</p> <pre><code>except: ei = sys.exc_info() raise ei[0], ei[1], ei[2].tb_next </code></pre> <p>tb_next is a read_only attribute, so I don't know of a way to remove stuff from the bottom. You might be able to screw with the properties mechanism to allow access to the property, but I don't know how to do that.</p>
9
2012-12-16T05:50:38Z
[ "python", "traceback" ]
How can I modify a Python traceback object when raising an exception?
1,603,940
<p>I'm working on a Python library used by third-party developers to write extensions for our core application.</p> <p>I'd like to know if it's possible to modify the traceback when raising exceptions, so the last stack frame is the call to the library function in the developer's code, rather than the line in the library that raised the exception. There are also a few frames at the bottom of the stack containing references to functions used when first loading the code that I'd ideally like to remove too.</p> <p>Thanks in advance for any advice!</p>
11
2009-10-21T22:08:06Z
39,747,516
<p>This code might be of interest for you.</p> <p>It takes a traceback and removes the first file, which should not be shown. Then it simulates the Python behavior:</p> <pre><code>Traceback (most recent call last): </code></pre> <p>will only be shown if the traceback contains more than one file. This looks exactly as if my extra frame was not there.</p> <p>Here my code, assuming there is a string <code>text</code>:</p> <pre><code>try: exec(text) except: # we want to format the exception as if no frame was on top. exp, val, tb = sys.exc_info() listing = traceback.format_exception(exp, val, tb) # remove the entry for the first frame del listing[1] files = [line for line in listing if line.startswith(" File")] if len(files) == 1: # only one file, remove the header. del listing[0] print("".join(listing), file=sys.stderr) sys.exit(1) </code></pre>
0
2016-09-28T12:27:44Z
[ "python", "traceback" ]
How can I work out the class hierarchy given an object instance in Python?
1,603,964
<p>Is there anyway to discover the base class of a class in Python?</p> <p>For given the following class definitions:</p> <pre><code>class A: def speak(self): print "Hi" class B(A): def getName(self): return "Bob" </code></pre> <p>If I received an instance of an object I can easily work out that it is a B by doing the following:</p> <pre><code>instance = B() print B.__class__.__name__ </code></pre> <p>Which prints the class name 'B' as expected.</p> <p>Is there anyway to discover that the instance of an object inherits from a base class as well as the actual class?</p> <p>Or is that just not how objects in Python work?</p>
2
2009-10-21T22:11:59Z
1,603,987
<pre><code>b = B() b.__class__ b.__class__.__base__ b.__class__.__bases__ b.__class__.__base__.__subclasses__() </code></pre> <p>I strongly recommend checking out ipython and use the tab completion :-)</p>
5
2009-10-21T22:17:47Z
[ "python", "inheritance", "oop" ]
How can I work out the class hierarchy given an object instance in Python?
1,603,964
<p>Is there anyway to discover the base class of a class in Python?</p> <p>For given the following class definitions:</p> <pre><code>class A: def speak(self): print "Hi" class B(A): def getName(self): return "Bob" </code></pre> <p>If I received an instance of an object I can easily work out that it is a B by doing the following:</p> <pre><code>instance = B() print B.__class__.__name__ </code></pre> <p>Which prints the class name 'B' as expected.</p> <p>Is there anyway to discover that the instance of an object inherits from a base class as well as the actual class?</p> <p>Or is that just not how objects in Python work?</p>
2
2009-10-21T22:11:59Z
1,604,131
<p>If instead of discovery of the baseclass (i.e reflection) you know the desired class in advance you could use the following <a href="http://python.org/doc/2.5/lib/built-in-funcs.html" rel="nofollow">built in functions</a></p> <p>eg:</p> <pre><code># With classes from original Question defined &gt;&gt;&gt; instance = A() &gt;&gt;&gt; B_instance = B() &gt;&gt;&gt; isinstance(instance, A) True &gt;&gt;&gt; isinstance(instance, B) False &gt;&gt;&gt; isinstance(B_instance, A) # Note it returns true if instance is a subclass True &gt;&gt;&gt; isinstance(B_instance, B) True &gt;&gt;&gt; issubclass(B, A) True </code></pre> <blockquote> <p><strong>isinstance( object, classinfo)</strong> Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof. Also return true if classinfo is a type object and object is an object of that type. If object is not a class instance or an object of the given type, the function always returns false. If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects, or may recursively contain other such tuples (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised. Changed in version 2.2: Support for a tuple of type information was added. </p> <p><strong>issubclass( class, classinfo)</strong> Return true if class is a subclass (direct or indirect) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised. Changed in version 2.3: Support for a tuple of type information was added.</p> </blockquote>
0
2009-10-21T23:00:15Z
[ "python", "inheritance", "oop" ]
How can I work out the class hierarchy given an object instance in Python?
1,603,964
<p>Is there anyway to discover the base class of a class in Python?</p> <p>For given the following class definitions:</p> <pre><code>class A: def speak(self): print "Hi" class B(A): def getName(self): return "Bob" </code></pre> <p>If I received an instance of an object I can easily work out that it is a B by doing the following:</p> <pre><code>instance = B() print B.__class__.__name__ </code></pre> <p>Which prints the class name 'B' as expected.</p> <p>Is there anyway to discover that the instance of an object inherits from a base class as well as the actual class?</p> <p>Or is that just not how objects in Python work?</p>
2
2009-10-21T22:11:59Z
1,604,219
<p>The inspect module is really powerful also:</p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; inst = B() &gt;&gt;&gt; inspect.getmro(inst.__class__) (&lt;class __main__.B at 0x012B42A0&gt;, &lt;class __main__.A at 0x012B4210&gt;) </code></pre>
6
2009-10-21T23:28:10Z
[ "python", "inheritance", "oop" ]
How can I work out the class hierarchy given an object instance in Python?
1,603,964
<p>Is there anyway to discover the base class of a class in Python?</p> <p>For given the following class definitions:</p> <pre><code>class A: def speak(self): print "Hi" class B(A): def getName(self): return "Bob" </code></pre> <p>If I received an instance of an object I can easily work out that it is a B by doing the following:</p> <pre><code>instance = B() print B.__class__.__name__ </code></pre> <p>Which prints the class name 'B' as expected.</p> <p>Is there anyway to discover that the instance of an object inherits from a base class as well as the actual class?</p> <p>Or is that just not how objects in Python work?</p>
2
2009-10-21T22:11:59Z
1,604,936
<p>Another way to get the class hierarchy is to access the <strong>mro</strong> attribute:</p> <pre><code>class A(object): pass class B(A): pass instance = B() print(instance.__class__.__mro__) # (&lt;class '__main__.B'&gt;, &lt;class '__main__.A'&gt;, &lt;type 'object'&gt;) </code></pre> <p>Note that in Python 2.x, you must use "new-style" objects to ensure they have the <strong>mro</strong> attribute. You do this by declaring </p> <pre><code>class A(object): </code></pre> <p>instead of </p> <pre><code>class A(): </code></pre> <p>See <a href="http://www.python.org/doc/newstyle/" rel="nofollow">http://www.python.org/doc/newstyle/</a> and <a href="http://www.python.org/download/releases/2.3/mro/" rel="nofollow">http://www.python.org/download/releases/2.3/mro/</a> for more info new-style objects and mro (method resolution order).</p> <p>In Python 3.x, all objects are new-style objects, so you can use <strong>mro</strong> and simply declare objects this way:</p> <pre><code>class A(): </code></pre>
3
2009-10-22T03:54:54Z
[ "python", "inheritance", "oop" ]
Python SSH / SFTP Module?
1,603,984
<p>I've been looking around for a module which allows me to do SSH / SFTP functions in python without using POPEN to do it manually. Is there anything like this? I haven't found any real information on this, thanks!</p>
11
2009-10-21T22:17:15Z
1,604,000
<p>You're probably looking for the excellent paramiko library:</p> <p><a href="http://www.paramiko.org/" rel="nofollow">http://www.paramiko.org/</a></p>
13
2009-10-21T22:22:51Z
[ "python", "ssh", "sftp" ]
Python SSH / SFTP Module?
1,603,984
<p>I've been looking around for a module which allows me to do SSH / SFTP functions in python without using POPEN to do it manually. Is there anything like this? I haven't found any real information on this, thanks!</p>
11
2009-10-21T22:17:15Z
1,604,001
<p>paramiko works nicely: <a href="http://www.paramiko.org/" rel="nofollow">Paramiko Homepage</a></p>
4
2009-10-21T22:22:52Z
[ "python", "ssh", "sftp" ]
Python SSH / SFTP Module?
1,603,984
<p>I've been looking around for a module which allows me to do SSH / SFTP functions in python without using POPEN to do it manually. Is there anything like this? I haven't found any real information on this, thanks!</p>
11
2009-10-21T22:17:15Z
9,101,477
<p>Depending on what you're looking to do over ssh, you might also benefit from looking at the pexpect library: <a href="http://www.noah.org/wiki/pexpect" rel="nofollow">http://www.noah.org/wiki/pexpect</a></p>
1
2012-02-01T18:51:13Z
[ "python", "ssh", "sftp" ]
Python SSH / SFTP Module?
1,603,984
<p>I've been looking around for a module which allows me to do SSH / SFTP functions in python without using POPEN to do it manually. Is there anything like this? I haven't found any real information on this, thanks!</p>
11
2009-10-21T22:17:15Z
34,361,424
<p>For SFTP, you can use <a href="https://pypi.python.org/pypi/pysftp" rel="nofollow">pysftp</a>, which is a thin wrapper over paramiko's SFTPClient (<code>pip install sftp</code>).</p> <p>Example to download a file:</p> <pre><code>import pysftp #pip install sftp import sys hostname = "128.65.45.12" username = "bob" password = "123456" sftp = pysftp.Connection(hostname, username=username, password=password) sftp.get('/data/word_vectors/GoogleNews-vectors-negative300.txt', preserve_mtime=True) print('done') </code></pre>
1
2015-12-18T18:00:17Z
[ "python", "ssh", "sftp" ]
how to put in transaction
1,604,021
<p>I have a class:</p> <pre><code>class AccountTransaction(db.Model): account = db.ReferenceProperty(reference_class=Account) tran_date = db.DateProperty() debit_credit = db.IntegerProperty() ## -1, 1 amount = db.FloatProperty() comment = db.StringProperty() pair = db.SelfReferenceProperty() </code></pre> <p>so, what I want is to make a Save() method which would run the following steps in the transaction:</p> <ul> <li>to save AccountTransaction</li> <li>to save paired AccountTransaction (the pair of paired transaction is self - circular reference)</li> <li>to update balances of each of the two Accounts - the account of primary &amp; the account of paired transaction</li> </ul> <p>It is possible that the parents of transactions be the their Accounts, but yet it seems impossible to make an entity group of these entities. </p> <p>Described in terms of RDBMS, this means that I want that one table has two foreign keys (one entity - two parents). What to do?</p> <p>At first, I tried not to manage the balances, but it seems to slow to calculate it every time ...</p> <p>What to do?</p>
1
2009-10-21T22:29:42Z
1,605,639
<p>Because your Account entities can't all be in the same entity group, you can't perform an update in a single transaction. There are techniques to do this, particularly in the 'money transfer' case you've encountered - I wrote <a href="http://blog.notdot.net/2009/9/Distributed-Transactions-on-App-Engine" rel="nofollow">a blog post</a> about this exact subject, in fact.</p>
1
2009-10-22T07:56:50Z
[ "python", "google-app-engine" ]
Parsing a text file with Python?
1,604,074
<p>I have to do an assignment where i have a .txt file that contains something like this<br /> p<br /> There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain... </p> <p>h1<br /> this is another example of what this text file looks like </p> <p>i am suppose to write a python code that parses this text file and creates and xhtml file<br /> I need to find a starting point for this project because i am very new to python and not familiar with alot of this stuff.<br /> This python code is suppose to take each of these "tags" from this text file and put them into an xhtml file I hope that what i ask makes sense to you.<br /> Any help is greatly appreciated,<br /> Thanks in advance!<br /> -bojan</p>
1
2009-10-21T22:43:22Z
1,604,104
<p>Rather than going directly from the text file you describe to an XHTML file, I would transform it into an intermediate in-memory representation first.</p> <p>So I would build classes to represent the <code>p</code> and <code>h1</code> tags, and then go through the text file and build those objects and put them into a list (or even a more complex object, but from the looks of your file a list should be sufficient). Then I would pass the list to another function that would loop through the <code>p</code> and <code>h1</code> objects and output them as XHTML.</p> <p>As an added bonus, I would make each tag object (say, <code>Paragraph</code> and <code>Heading1</code> classes) implement an <code>as_xhtml()</code> method, and delegate the actual formatting to that method. Then the XHTML output loop could be something like:</p> <pre><code>for tag in input_tags: xhtml_file.write(tag.as_xhtml()) </code></pre>
1
2009-10-21T22:52:25Z
[ "python", "string", "parsing", "text-files" ]
Parsing a text file with Python?
1,604,074
<p>I have to do an assignment where i have a .txt file that contains something like this<br /> p<br /> There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain... </p> <p>h1<br /> this is another example of what this text file looks like </p> <p>i am suppose to write a python code that parses this text file and creates and xhtml file<br /> I need to find a starting point for this project because i am very new to python and not familiar with alot of this stuff.<br /> This python code is suppose to take each of these "tags" from this text file and put them into an xhtml file I hope that what i ask makes sense to you.<br /> Any help is greatly appreciated,<br /> Thanks in advance!<br /> -bojan</p>
1
2009-10-21T22:43:22Z
1,604,888
<p>You say you're very new to Python, so I'll start at the very low-level. You can iterate over the lines in a file very simply in Python</p> <pre><code>fyle = open("contents.txt") for lyne in fyle : # Do string processing here fyle.close() </code></pre> <p>Now how to parse it. If each formatting directive (e.g. p, h1), is on a separate line, you can check that easily. I'd build up a dictionary of handlers and get the handler like so:</p> <pre><code>handlers= {"p": # p tag handler "h1": # h1 tag handler } # ... in the loop if lyne.rstrip() in handlers : # strip to remove trailing whitespace # close current handler? # start new handler? else : # pass string to current handler </code></pre> <p>You could do what <a href="http://stackoverflow.com/questions/1604074/parsing-a-text-file-with-python/1604104#1604104">Daniel Pryden suggested</a> and create an in-memory data structure first, and then serialize that the XHTML. In that case, the handlers would know how to build the objects corresponding to each tag. But I think the simpler solution, especially if you don't have lots of time, you have is just to go straight to XHTML, keeping a stack of the current enclosed tags. In that case your "handler" may just be some simple logic to write the tags to the output file/string.</p> <p>I can't say more without knowing the specifics of your problem. And besides, I don't want to do all your homework for you. This should give you a good start.</p>
9
2009-10-22T03:31:21Z
[ "python", "string", "parsing", "text-files" ]
starting my own threads within python paste
1,604,079
<p>I'm writing a web application using pylons and paste. I have some work I want to do after an HTTP request is finished (send some emails, write some stuff to the db, etc) that I don't want to block the HTTP request on.</p> <p>If I start a thread to do this work, is that OK? I always see this stuff about paste killing off hung threads, etc. Will it kill my threads which are doing work?</p> <p>What else can I do here? Is there a way I can make the request return but have some code run after it's done?</p> <p>Thanks.</p>
1
2009-10-21T22:43:57Z
1,604,402
<p>You could use a thread approach (maybe setting the <a href="http://docs.python.org/library/threading.html#threading.Thread.daemon" rel="nofollow">Thead.daemon</a> property would help--but I'm not sure). </p> <p>However, I would suggest looking into a task queuing system. You can place a task on a queue (which is very fast), then a listener can handle the tasks asynchronously, allowing the HTTP request to return quickly. There are two task queues that I know of for Django:</p> <ul> <li><a href="http://code.google.com/p/django-queue-service/wiki/DjangoQueueService" rel="nofollow">Django Queue Service</a> </li> <li><a href="http://ask.github.com/celery/introduction.html" rel="nofollow">Celery</a></li> </ul> <p>You could also consider using an more "enterprise" messaging solution, such as <a href="http://www.rabbitmq.com/" rel="nofollow">RabbitMQ</a> or <a href="http://activemq.apache.org/" rel="nofollow">ActiveMQ</a>.</p> <p><strong>Edit</strong>: <a href="http://stackoverflow.com/questions/454944/advice-on-python-django-and-message-queues/455024#455024">previous answer</a> with some good pointers.</p>
0
2009-10-22T00:28:54Z
[ "python", "pylons", "paste" ]
starting my own threads within python paste
1,604,079
<p>I'm writing a web application using pylons and paste. I have some work I want to do after an HTTP request is finished (send some emails, write some stuff to the db, etc) that I don't want to block the HTTP request on.</p> <p>If I start a thread to do this work, is that OK? I always see this stuff about paste killing off hung threads, etc. Will it kill my threads which are doing work?</p> <p>What else can I do here? Is there a way I can make the request return but have some code run after it's done?</p> <p>Thanks.</p>
1
2009-10-21T22:43:57Z
1,639,490
<p>I think the best solution is messaging system because it can be configured to not loose the task if the pylons process goes down. I would always use processes over threads especially in this case. If you are using python 2.6+ use the built in <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing</a> or you can always install the processing module which you can find on pypi (I can't post link because of I am a new user). </p>
0
2009-10-28T19:19:36Z
[ "python", "pylons", "paste" ]
starting my own threads within python paste
1,604,079
<p>I'm writing a web application using pylons and paste. I have some work I want to do after an HTTP request is finished (send some emails, write some stuff to the db, etc) that I don't want to block the HTTP request on.</p> <p>If I start a thread to do this work, is that OK? I always see this stuff about paste killing off hung threads, etc. Will it kill my threads which are doing work?</p> <p>What else can I do here? Is there a way I can make the request return but have some code run after it's done?</p> <p>Thanks.</p>
1
2009-10-21T22:43:57Z
1,768,292
<p>Take a look at gearman, it was specifically made for farming out tasks to 'workers' to handle. They can even handle it in a different language entirely. You can come back and ask if the task was completed, or just let it complete. That should work well for many tasks.</p> <p>If you absolutely need to ensure it was completed, I'd suggest queuing tasks in a database or somewhere persistent, then have a separate process that runs through it ensuring each one gets handled appropriately.</p>
0
2009-11-20T04:10:49Z
[ "python", "pylons", "paste" ]
starting my own threads within python paste
1,604,079
<p>I'm writing a web application using pylons and paste. I have some work I want to do after an HTTP request is finished (send some emails, write some stuff to the db, etc) that I don't want to block the HTTP request on.</p> <p>If I start a thread to do this work, is that OK? I always see this stuff about paste killing off hung threads, etc. Will it kill my threads which are doing work?</p> <p>What else can I do here? Is there a way I can make the request return but have some code run after it's done?</p> <p>Thanks.</p>
1
2009-10-21T22:43:57Z
1,843,498
<p>To answer your basic question directly, you should be able to use threads just as you'd like. The "killing hung threads" part is paste cleaning up its own threads, not yours.</p> <p>There are other packages that might help, etc, but I'd suggest you start with simple threads and see how far you get. Only then will you know what you need next.</p> <p>(Note, "Thread.daemon" should be mostly irrelevant to you here. Setting that true will ensure a thread you start will not prevent the entire process from exiting. Doing so would mean, however, that if the process exited "cleanly" (as opposed to being forced to exit) your thread would be terminated even if it wasn't done its work. Whether that's a problem, and how you handle things like that, depend entirely on your own requirements and design.</p>
0
2009-12-03T22:36:41Z
[ "python", "pylons", "paste" ]
Interacting with SVN from appengine
1,604,220
<p>I've got a couple of projects where it would be useful to be able to interact with an SVN server from appengine.</p> <ul> <li>Pull specific files from the svn (fairly easy, since there is a web interface which I can grab the data off automatically, but how do I authenticate)</li> <li>Commit changes to the svn (this is the really hard/important part)</li> <li>Possibly run an SVN server (from an appengine app, I'm guessing this isn't possible)</li> </ul> <p>I would prefer a python solution, but I can survive with java if I must</p>
5
2009-10-21T23:28:20Z
1,604,249
<p>you can try using <a href="http://svnkit.com/" rel="nofollow">SVNKit</a> with the java runtime</p>
4
2009-10-21T23:39:30Z
[ "java", "python", "svn", "google-app-engine" ]
Interacting with SVN from appengine
1,604,220
<p>I've got a couple of projects where it would be useful to be able to interact with an SVN server from appengine.</p> <ul> <li>Pull specific files from the svn (fairly easy, since there is a web interface which I can grab the data off automatically, but how do I authenticate)</li> <li>Commit changes to the svn (this is the really hard/important part)</li> <li>Possibly run an SVN server (from an appengine app, I'm guessing this isn't possible)</li> </ul> <p>I would prefer a python solution, but I can survive with java if I must</p>
5
2009-10-21T23:28:20Z
1,604,792
<p>DryDrop (<a href="http://drydrop.binaryage.com/" rel="nofollow">http://drydrop.binaryage.com/</a>) is a Git based solution you may want to look at for comparison of what you're trying to do.</p>
3
2009-10-22T03:00:42Z
[ "java", "python", "svn", "google-app-engine" ]
Interacting with SVN from appengine
1,604,220
<p>I've got a couple of projects where it would be useful to be able to interact with an SVN server from appengine.</p> <ul> <li>Pull specific files from the svn (fairly easy, since there is a web interface which I can grab the data off automatically, but how do I authenticate)</li> <li>Commit changes to the svn (this is the really hard/important part)</li> <li>Possibly run an SVN server (from an appengine app, I'm guessing this isn't possible)</li> </ul> <p>I would prefer a python solution, but I can survive with java if I must</p>
5
2009-10-21T23:28:20Z
3,500,644
<p>You can talk to a svn server(if setup with apache running <a href="http://svnbook.red-bean.com/en/1.0/ch06s04.html" rel="nofollow">mod_dav_svn</a>) using the <a href="http://en.wikipedia.org/wiki/WebDAV" rel="nofollow">webdav</a> protocol. See <a href="http://svn.apache.org/repos/asf/subversion/trunk/notes/http-and-webdav/" rel="nofollow">apache's implementation details</a> Problem is that <a href="http://code.google.com/appengine/" rel="nofollow">google appengine</a>'s <a href="http://code.google.com/appengine/docs/python/urlfetch/" rel="nofollow">urlfetch</a> system doesn't allow for HTTP request methods other then GET, POST, HEAD, PUT and DELETE. (webdav uses custom request methods like PROPFIND, PROPPATCH, etc..) So at this time you are restricted to just viewing the contents of the svn server.</p> <p>You can however use google appengine to implement a webdav provider. Have a look at the <a href="http://code.google.com/p/gae-webdav/" rel="nofollow">gae-webdav</a> project for more information.</p>
1
2010-08-17T08:32:32Z
[ "java", "python", "svn", "google-app-engine" ]
Do dictionaries in Python have a single repr value?
1,604,281
<p>In this <a href="http://stackoverflow.com/questions/1600591/using-a-python-dictionary-as-a-key">question</a>, it was suggested that calling repr on a dictionary would be a good way to store it in another dictionary. This would depend on repr being the same regardless of how the keys are ordered. Is this the case?</p> <p>PS. the most elegant solution to the original problem was actually using frozenset</p>
2
2009-10-21T23:50:34Z
1,604,299
<p>That's not the case -- key ordering is arbitrary.</p> <p>If you'd like to use a dictionary as a key, it should be converted into a fixed form (such as a sorted tuple). Of course, this won't work for dictionaries with non-hashable values.</p>
2
2009-10-21T23:55:59Z
[ "python" ]
Do dictionaries in Python have a single repr value?
1,604,281
<p>In this <a href="http://stackoverflow.com/questions/1600591/using-a-python-dictionary-as-a-key">question</a>, it was suggested that calling repr on a dictionary would be a good way to store it in another dictionary. This would depend on repr being the same regardless of how the keys are ordered. Is this the case?</p> <p>PS. the most elegant solution to the original problem was actually using frozenset</p>
2
2009-10-21T23:50:34Z
1,604,310
<p>No, the order that keys are added to a dictionary can affect the internal data structure. When two items have the same hash value and end up in the same bucket then the order they are added to the dictionary matters.</p> <pre><code>&gt;&gt;&gt; (1).__hash__() 1 &gt;&gt;&gt; (1 &lt;&lt; 32).__hash__() 1 &gt;&gt;&gt; repr({1: 'one', 1 &lt;&lt; 32: 'not one'}) "{1: 'one', 4294967296L: 'not one'}" &gt;&gt;&gt; repr({1 &lt;&lt; 32: 'not one', 1: 'one'}) "{4294967296L: 'not one', 1: 'one'}" </code></pre>
6
2009-10-21T23:59:28Z
[ "python" ]
Do dictionaries in Python have a single repr value?
1,604,281
<p>In this <a href="http://stackoverflow.com/questions/1600591/using-a-python-dictionary-as-a-key">question</a>, it was suggested that calling repr on a dictionary would be a good way to store it in another dictionary. This would depend on repr being the same regardless of how the keys are ordered. Is this the case?</p> <p>PS. the most elegant solution to the original problem was actually using frozenset</p>
2
2009-10-21T23:50:34Z
1,604,375
<p>If you want to store a dictionary in another dictionary, there is no need to do any transformations first. If you want to use a dictionary as the key to another dictionary, then you need to transform it, ideally into a sorted tuple of key/value tuples.</p>
0
2009-10-22T00:21:25Z
[ "python" ]
Object oriented design?
1,604,391
<p>I'm trying to learn object oriented programming, but am having a hard time overcoming my structured programming background (mainly C, but many others over time). I thought I'd write a simple check register program as an exercise. I put something together pretty quickly (python is a great language), with my data in some global variables and with a bunch of functions. I can't figure out if this design can be improved by creating a number of classes to encapsulate some of the data and functions and, if so, how to change the design.</p> <p>My data is basically a list of accounts ['checking', 'saving', 'Amex'], a list of categories ['food', 'shelter', 'transportation'] and lists of dicts that represent transactions [{'date':xyz, 'cat':xyz, 'amount':xyz, 'description':xzy]. Each account has an associated list of dicts.</p> <p>I then have functions at the account level (create-acct(), display-all-accts(), etc.) and the transaction level (display-entries-in-account(), enter-a-transaction(), edit-a-transaction(), display-entries-between-dates(), etc.)</p> <p>The user sees a list of accounts, then can choose an account and see the underlying transactions, with ability to add, delete, edit, etc. the accounts and transactions.</p> <p>I currently implement everything in one large class, so that I can use self.variable throughout, rather than explicit globals.</p> <p>In short, I'm trying to figure out if re-organizing this into some classes would be useful and, if so, how to design those classes. I've read some oop books (most recently Object-Oriented Thought Process). I like to think my existing design is readable and does not repeat itself.</p> <p>Any suggestions would be appreciated.</p>
5
2009-10-22T00:25:16Z
1,604,398
<p>Not a direct answer to your question but O'Reilly's <a href="http://rads.stackoverflow.com/amzn/click/0596008678" rel="nofollow">Head First Object-Oriented Analysis and Design</a> is an excellent place to start.</p> <p>Followed by <a href="http://rads.stackoverflow.com/amzn/click/0596007124" rel="nofollow">Head First Design Patterns</a></p>
5
2009-10-22T00:27:50Z
[ "python", "oop" ]
Object oriented design?
1,604,391
<p>I'm trying to learn object oriented programming, but am having a hard time overcoming my structured programming background (mainly C, but many others over time). I thought I'd write a simple check register program as an exercise. I put something together pretty quickly (python is a great language), with my data in some global variables and with a bunch of functions. I can't figure out if this design can be improved by creating a number of classes to encapsulate some of the data and functions and, if so, how to change the design.</p> <p>My data is basically a list of accounts ['checking', 'saving', 'Amex'], a list of categories ['food', 'shelter', 'transportation'] and lists of dicts that represent transactions [{'date':xyz, 'cat':xyz, 'amount':xyz, 'description':xzy]. Each account has an associated list of dicts.</p> <p>I then have functions at the account level (create-acct(), display-all-accts(), etc.) and the transaction level (display-entries-in-account(), enter-a-transaction(), edit-a-transaction(), display-entries-between-dates(), etc.)</p> <p>The user sees a list of accounts, then can choose an account and see the underlying transactions, with ability to add, delete, edit, etc. the accounts and transactions.</p> <p>I currently implement everything in one large class, so that I can use self.variable throughout, rather than explicit globals.</p> <p>In short, I'm trying to figure out if re-organizing this into some classes would be useful and, if so, how to design those classes. I've read some oop books (most recently Object-Oriented Thought Process). I like to think my existing design is readable and does not repeat itself.</p> <p>Any suggestions would be appreciated.</p>
5
2009-10-22T00:25:16Z
1,604,403
<p>"My data is basically a list of accounts"</p> <p>Account is a class.</p> <p>"dicts that represent transactions"</p> <p>Transaction appears to be a class. You happen to have elected to represent this as a dict.</p> <p>That's your first pass at OO design. Focus on the Responsibilities and Collaborators.</p> <p>You have at least two classes of objects.</p>
3
2009-10-22T00:29:07Z
[ "python", "oop" ]
Object oriented design?
1,604,391
<p>I'm trying to learn object oriented programming, but am having a hard time overcoming my structured programming background (mainly C, but many others over time). I thought I'd write a simple check register program as an exercise. I put something together pretty quickly (python is a great language), with my data in some global variables and with a bunch of functions. I can't figure out if this design can be improved by creating a number of classes to encapsulate some of the data and functions and, if so, how to change the design.</p> <p>My data is basically a list of accounts ['checking', 'saving', 'Amex'], a list of categories ['food', 'shelter', 'transportation'] and lists of dicts that represent transactions [{'date':xyz, 'cat':xyz, 'amount':xyz, 'description':xzy]. Each account has an associated list of dicts.</p> <p>I then have functions at the account level (create-acct(), display-all-accts(), etc.) and the transaction level (display-entries-in-account(), enter-a-transaction(), edit-a-transaction(), display-entries-between-dates(), etc.)</p> <p>The user sees a list of accounts, then can choose an account and see the underlying transactions, with ability to add, delete, edit, etc. the accounts and transactions.</p> <p>I currently implement everything in one large class, so that I can use self.variable throughout, rather than explicit globals.</p> <p>In short, I'm trying to figure out if re-organizing this into some classes would be useful and, if so, how to design those classes. I've read some oop books (most recently Object-Oriented Thought Process). I like to think my existing design is readable and does not repeat itself.</p> <p>Any suggestions would be appreciated.</p>
5
2009-10-22T00:25:16Z
1,604,426
<p>There are many 'mindsets' that you could adopt to help in the design process (some of which point towards OO and some that don't). I think it is often better to start with questions rather than answers (i.e. rather than say, 'how can I apply inheritance to this' you should ask how this system might expect to change over time).</p> <p>Here's a few questions to answer that might point you towards design principles:</p> <ul> <li>Are other's going to use this API? Are they likely to break it? (<strong>info hiding</strong>)</li> <li>do I need to deploy this across many machines? (<strong>state management, lifecycle management</strong>)</li> <li>do i need to interoperate with other systems, runtimes, languages? (<strong>abstraction and standards</strong>)</li> <li>what are my performance constraints? (<strong>state management, lifecycle management</strong>)</li> <li>what kind of security environment does this component live in? (<strong>abstraction, info hiding, interoperability</strong>)</li> <li>how would i construct my objects, assuming I used some? (<strong>configuration, inversion of control, object decoupling, hiding implementation details</strong>)</li> </ul> <p>These aren't direct answers to your question, but they might put you in the right frame of mind to answer it yourself. :)</p>
1
2009-10-22T00:37:55Z
[ "python", "oop" ]
Object oriented design?
1,604,391
<p>I'm trying to learn object oriented programming, but am having a hard time overcoming my structured programming background (mainly C, but many others over time). I thought I'd write a simple check register program as an exercise. I put something together pretty quickly (python is a great language), with my data in some global variables and with a bunch of functions. I can't figure out if this design can be improved by creating a number of classes to encapsulate some of the data and functions and, if so, how to change the design.</p> <p>My data is basically a list of accounts ['checking', 'saving', 'Amex'], a list of categories ['food', 'shelter', 'transportation'] and lists of dicts that represent transactions [{'date':xyz, 'cat':xyz, 'amount':xyz, 'description':xzy]. Each account has an associated list of dicts.</p> <p>I then have functions at the account level (create-acct(), display-all-accts(), etc.) and the transaction level (display-entries-in-account(), enter-a-transaction(), edit-a-transaction(), display-entries-between-dates(), etc.)</p> <p>The user sees a list of accounts, then can choose an account and see the underlying transactions, with ability to add, delete, edit, etc. the accounts and transactions.</p> <p>I currently implement everything in one large class, so that I can use self.variable throughout, rather than explicit globals.</p> <p>In short, I'm trying to figure out if re-organizing this into some classes would be useful and, if so, how to design those classes. I've read some oop books (most recently Object-Oriented Thought Process). I like to think my existing design is readable and does not repeat itself.</p> <p>Any suggestions would be appreciated.</p>
5
2009-10-22T00:25:16Z
1,604,427
<p>You don't have to throw out structured programming to do object-oriented programming. The code is still structured, it just belongs to the objects rather than being separate from them.</p> <p>In classical programming, code is the driving force that operates on data, leading to a dichotomy (and the possibility that code can operate on the <em>wrong</em> data).</p> <p>In OO, data and code are inextricably entwined - an object contains both data and the code to operate on that data (although technically the code (and sometimes some data) belongs to the class rather than an individual object). Any client code that wants to use those objects should do so only by using the code within that object. This prevents the code/data mismatch problem.</p> <p>For a bookkeeping system, I'd approach it as follows:</p> <ol> <li>Low-level objects are accounts and categories (actually, in accounting, there's no difference between these, this is a false separation only exacerbated by Quicken et al to separate balance sheet items from P&amp;L - I'll refer to them as accounts only). An account object consists of (for example) an account code, name and starting balance, although in the accounting systems I've worked on, starting balance is always zero - I've always used a "startup" transaction to set the balanaces initially.</li> <li>Transactions are a balanced object which consist of a group of accounts/categories with associated movements (changes in dollar value). By balanced, I mean they must sum to zero (this is the crux of double entry accounting). This means it's a date, description and an array or vector of elements, each containing an account code and value.</li> <li>The overall accounting "object" (the ledger) is then simply the list of all accounts and transactions.</li> </ol> <p>Keep in mind that this is the "back-end" of the system (the data model). You will hopefully have separate classes for viewing the data (the view) which will allow you to easily change it, depending on user preferences. For example, you may want the whole ledger, just the balance sheet or just the P&amp;L. Or you may want different date ranges.</p> <p>One thing I'd stress to make a good accounting system. You <em>do</em> need to think like a bookkeeper. By that I mean lose the artificial difference between "accounts" and "categories" since it will make your system a lot cleaner (you need to be able to have transactions between two asset-class accounts (such as a bank transfer) and this won't work if every transaction needs a "category". The data model should reflect the data, not the view.</p> <p>The only difficulty there is remembering that asset-class accounts have the opposite sign from which you expect (negative values for your cash-at-bank mean you have money in the bank and your very high <em>positive</em> value loan for that company sports car is a <em>debt</em>, for example). This will make the double-entry aspect work perfectly but you have to remember to reverse the signs of asset-class accounts (assets, liabilities and equity) when showing or printing the balance sheet.</p>
7
2009-10-22T00:38:02Z
[ "python", "oop" ]
Object oriented design?
1,604,391
<p>I'm trying to learn object oriented programming, but am having a hard time overcoming my structured programming background (mainly C, but many others over time). I thought I'd write a simple check register program as an exercise. I put something together pretty quickly (python is a great language), with my data in some global variables and with a bunch of functions. I can't figure out if this design can be improved by creating a number of classes to encapsulate some of the data and functions and, if so, how to change the design.</p> <p>My data is basically a list of accounts ['checking', 'saving', 'Amex'], a list of categories ['food', 'shelter', 'transportation'] and lists of dicts that represent transactions [{'date':xyz, 'cat':xyz, 'amount':xyz, 'description':xzy]. Each account has an associated list of dicts.</p> <p>I then have functions at the account level (create-acct(), display-all-accts(), etc.) and the transaction level (display-entries-in-account(), enter-a-transaction(), edit-a-transaction(), display-entries-between-dates(), etc.)</p> <p>The user sees a list of accounts, then can choose an account and see the underlying transactions, with ability to add, delete, edit, etc. the accounts and transactions.</p> <p>I currently implement everything in one large class, so that I can use self.variable throughout, rather than explicit globals.</p> <p>In short, I'm trying to figure out if re-organizing this into some classes would be useful and, if so, how to design those classes. I've read some oop books (most recently Object-Oriented Thought Process). I like to think my existing design is readable and does not repeat itself.</p> <p>Any suggestions would be appreciated.</p>
5
2009-10-22T00:25:16Z
1,604,703
<p>Rather than using dicts to represent your transactions, a better container would be a namedtuple from the collections module. A namedtuple is a subclass of tuple which allows you to reference it's items by name as well as index number.</p> <p>Since you may possibly have thousands of transactions in your journal lists, it pays to keep these items as small and light-weight as possible so that processing, sorting, searching, etc. is as fast and responsive as possible. A dict is a fairly heavy-weight object compared to a namedtuple which takes up no more memory than an ordinary tuple. A namedtuple also has the added advantage of keeping it's items in order, unlike a dict.</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; from collections import namedtuple &gt;&gt;&gt; sys.getsizeof((1,2,3,4,5,6,7,8)) 60 &gt;&gt;&gt; ntc = namedtuple('ntc', 'one two three four five six seven eight') &gt;&gt;&gt; xnt = ntc(1,2,3,4,5,6,7,8) &gt;&gt;&gt; sys.getsizeof(xnt) 60 &gt;&gt;&gt; xdic = dict(one=1, two=2, three=3, four=4, five=5, six=6, seven=7, eight=8) &gt;&gt;&gt; sys.getsizeof(xdic) 524 </code></pre> <p>So you see that's almost 9 times saving in memory for an eight item transaction. I'm using Python 3.1, so your milage may vary.</p>
-1
2009-10-22T02:18:27Z
[ "python", "oop" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
1,604,605
<p>A couple of implementations (just an illustration, not intended for use):</p> <pre><code>def to_int(bin): x = int(bin, 2) if bin[0] == '1': # "sign bit", big-endian x -= 2**len(bin) return x def to_int(bin): # from definition n = 0 for i, b in enumerate(reversed(bin)): if b == '1': if i != (len(bin)-1): n += 2**i else: # MSB n -= 2**i return n </code></pre>
1
2009-10-22T01:42:08Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
1,604,701
<pre><code>&gt;&gt;&gt; bits_in_word=12 &gt;&gt;&gt; int('111111111111',2)-(1&lt;&lt;bits_in_word) -1 </code></pre> <p>This works because:</p> <blockquote> <p>The two's complement of a binary number is defined as the value obtained by subtracting the number from a large power of two (specifically, from 2^N for an N-bit two's complement). The two's complement of the number then behaves like the negative of the original number in most arithmetic, and it can coexist with positive numbers in a natural way.</p> </blockquote>
6
2009-10-22T02:17:14Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
1,605,553
<p>It's not built in, but if you want unusual length numbers then you could use the <a href="http://python-bitstring.googlecode.com" rel="nofollow">bitstring</a> module.</p> <pre><code>&gt;&gt;&gt; from bitstring import Bits &gt;&gt;&gt; a = Bits(bin='111111111111') &gt;&gt;&gt; a.int -1 </code></pre> <p>The same object can equivalently be created in several ways, including</p> <pre><code>&gt;&gt;&gt; b = Bits(int=-1, length=12) </code></pre> <p>It just behaves like a string of bits of arbitrary length, and uses properties to get different interpretations:</p> <pre><code>&gt;&gt;&gt; print a.int, a.uint, a.bin, a.hex, a.oct -1 4095 111111111111 fff 7777 </code></pre>
13
2009-10-22T07:30:14Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
9,147,327
<p>DANGER: gnibbler's answer (currently the highest ranked) isn't correct.<br> Sadly, I can't figure out how to add a comment to it.</p> <p>Two's compliment subtracts off <code>(1&lt;&lt;bits)</code> if the highest bit is 1. Taking 8 bits for example, this gives a range of 127 to -128.</p> <p>A function for two's compliment of an int...</p> <pre><code>def twos_comp(val, bits): """compute the 2's compliment of int value val""" if (val &amp; (1 &lt;&lt; (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 &lt;&lt; bits) # compute negative value return val # return positive value as is </code></pre> <p>Going from a binary string is particularly easy...</p> <pre><code>binary_string = '1111' # or whatever... no '0b' prefix out = twos_comp(int(binary_string,2), len(binary_string)) </code></pre> <p>A bit more useful to me is going from hex values (32 bits in this example)...</p> <pre><code>hex_string = '0xFFFFFFFF' # or whatever... '0x' prefix doesn't matter out = twos_comp(int(hex_string,16), 32) </code></pre>
40
2012-02-05T06:14:32Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
26,534,436
<p>Since erikb85 brought up performance, here's <a href="http://stackoverflow.com/a/9147327/908494">travc's answer</a> against <a href="http://stackoverflow.com/a/1605553/908494">Scott Griffiths'</a>:</p> <pre><code>In [534]: a = [0b111111111111, 0b100000000000, 0b1, 0] * 1000 In [535]: %timeit [twos_comp(x, 12) for x in a] 100 loops, best of 3: 8.8 ms per loop In [536]: %timeit [bitstring.Bits(uint=x, length=12).int for x in a] 10 loops, best of 3: 55.9 ms per loop </code></pre> <p>So, <code>bitstring</code> is, as found in <a href="http://stackoverflow.com/questions/20845686/python-bit-array-performant/20846054#20846054">the other question</a>, almost an order of magnitude slower than <code>int</code>. But on the other hand, it's hard to beat the simplicity—I'm converting a <code>uint</code> to a bit-string then to an <code>int</code>; you'd have to work hard <em>not</em> to understand this, or to find anywhere to introduce a bug. And as Scott Griffiths' answer implies, there's a lot more flexibility to the class which might be useful to the same app. But on the third hand, travc's answer makes it clear what's actually happening—even a novice should be able to understand what conversion from an unsigned int to a 2s complement signed int means just from reading 2 lines of code.</p> <p>Anyway, unlike the other question, which was about directly manipulating bits, this one is all about doing arithmetic on fixed-length ints, just oddly-sized ones. So I'm guessing if you need performance, it's probably because you have a whole bunch of these things, so you probably want it to be vectorized. Adapting travc's answer to numpy:</p> <pre><code>def twos_comp_np(vals, bits): """compute the 2's compliment of array of int values vals""" vals[vals &amp; (1&lt;&lt;(bits-1)) != 0] -= (1&lt;&lt;bits) return vals </code></pre> <p>Now:</p> <pre><code>In [543]: a = np.array(a) In [544]: %timeit twos_comp_np(a.copy(), 12) 10000 loops, best of 3: 63.5 µs per loop </code></pre> <p>You could probably beat that with custom C code, but you probably don't have to.</p>
0
2014-10-23T18:03:44Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
29,036,858
<p>I'm using Python 3.4.0</p> <p>In Python 3 we have some problems with data types transformation.</p> <p>So... here I'll tell a tip for those (like me) that works a lot with hex strings.</p> <p>I'll take an hex data and make an complement it:</p> <pre><code>a = b'acad0109' compl = int(a,16)-pow(2,32) result=hex(compl) print(result) print(int(result,16)) print(bin(int(result,16))) </code></pre> <p>result = -1397948151 or -0x5352fef7 or '-0b1010011010100101111111011110111'</p>
0
2015-03-13T16:03:20Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
32,262,478
<p>Unfortunately there is no built-in function to cast an unsigned integer to a two's complement signed value, but we can define a function to do so using bitwise operations:</p> <pre><code>def s12(value): return -(value &amp; 0b100000000000) | (value &amp; 0b011111111111) </code></pre> <p>The first bitwise-and operation is used to sign-extend negative numbers (most significant bit is set), while the second is used to grab the remaining 11 bits. This works since integers in Python are treated as arbitrary precision two's complement values.</p> <p>You can then combine this with the <code>int</code> function to convert a string of binary digits into the unsigned integer form, then interpret it as a 12-bit signed value.</p> <pre><code>&gt;&gt;&gt; s12(int('111111111111', 2)) -1 &gt;&gt;&gt; s12(int('011111111111', 2)) 2047 &gt;&gt;&gt; s12(int('100000000000', 2)) -2048 </code></pre> <p>One nice property of this function is that it's idempotent, thus the value of an already signed value will not change.</p> <pre><code>&gt;&gt;&gt; s12(-1) -1 </code></pre>
0
2015-08-28T02:32:41Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
36,338,336
<p>This will give you the two's complement efficiently using bitwise logic:</p> <pre><code>def twos_complement(value, bitWidth): if value &gt;= 2**bitWidth: # This catches when someone tries to give a value that is out of range raise ValueError("Value: {} out of range of {}-bit value.".format(value, bitWidth)) else: return value - int((value &lt;&lt; 1) &amp; 2**bitWidth) </code></pre> <p>How it works:</p> <p>First, we make sure that the user has passed us a value that is within the range of the supplied bit range (e.g. someone gives us 0xFFFF and specifies 8 bits) Another solution to that problem would be to bitwise AND (&amp;) the value with (2**bitWidth)-1 </p> <p>To get the result, the value is shifted by 1 bit to the left. This moves the MSB of the value (the sign bit) into position to be anded with <code>2**bitWidth</code>. When the sign bit is '0' the subtrahend becomes 0 and the result is <code>value - 0</code>. When the sign bit is '1' the subtrahend becomes <code>2**bitWidth</code> and the result is <code>value - 2**bitWidth</code> </p> <p>Example 1: If the parameters are value=0xFF (255d, b11111111) and bitWidth=8</p> <ol> <li>0xFF - int((0xFF &lt;&lt; 1) &amp; 2**8)</li> <li>0xFF - int((0x1FE) &amp; 0x100)</li> <li>0xFF - int(0x100)</li> <li>255 - 256</li> <li>-1</li> </ol> <p>Example 2: If the parameters are value=0x1F (31d, b11111) and bitWidth=6</p> <ol> <li>0x1F - int((0x1F &lt;&lt; 1) &amp; 2**6)</li> <li>0x1F - int((0x3E) &amp; 0x40)</li> <li>0x1F - int(0x00)</li> <li>31 - 0</li> <li>31</li> </ol> <p>Example 3: value = 0x80, bitWidth = 7</p> <p><code>ValueError: Value: 128 out of range of 7-bit value.</code></p> <p>Example 4: value = 0x80, bitWitdh = 8</p> <ol> <li>0x80 - int((0x80 &lt;&lt; 1) &amp; 2**8)</li> <li>0x80 - int((0x100) &amp; 0x100)</li> <li>0x80 - int(0x100)</li> <li>128 - 256</li> <li>-128</li> </ol> <p>Now, using what others have already posted, pass your bitstring into int(bitstring,2) and pass to the twos_complement method's value parameter.</p>
0
2016-03-31T16:01:15Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
37,075,643
<p>Since Python 3.2, there are built-in functions for byte manipulation: <a href="https://docs.python.org/3.4/library/stdtypes.html#int.to_bytes" rel="nofollow">https://docs.python.org/3.4/library/stdtypes.html#int.to_bytes</a>.</p> <p>By combining to_bytes and from_bytes, you get</p> <pre class="lang-py prettyprint-override"><code>def twos(val_str, bytes): import sys val = int(val_str, 2) b = val.to_bytes(bytes, byteorder=sys.byteorder, signed=False) return int.from_bytes(b, byteorder=sys.byteorder, signed=True) </code></pre> <p>Check:</p> <pre class="lang-py prettyprint-override"><code>twos('11111111', 1) # gives -1 twos('01111111', 1) # gives 127 </code></pre> <p>For older versions of Python, travc's answer is good but it does not work for negative values if one would like to work with integers instead of strings. A twos' complement function for which f(f(val)) == val is true for each val is:</p> <pre class="lang-py prettyprint-override"><code>def twos_complement(val, nbits): """Compute the 2's complement of int value val""" if val &lt; 0: val = (1 &lt;&lt; nbits) + val else: if (val &amp; (1 &lt;&lt; (nbits - 1))) != 0: # If sign bit is set. # compute negative value. val = val - (1 &lt;&lt; nbits) return val </code></pre>
0
2016-05-06T15:01:34Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
38,088,563
<p>This works for 3 bytes. <a href="https://repl.it/C6zx/3" rel="nofollow">Live code is here</a></p> <pre><code>def twos_compliment(byte_arr): a = byte_arr[0]; b = byte_arr[1]; c = byte_arr[2] out = ((a&lt;&lt;16)&amp;0xff0000) | ((b&lt;&lt;8)&amp;0xff00) | (c&amp;0xff) neg = (a &amp; (1&lt;&lt;7) != 0) # first bit of a is the "signed bit." if it's a 1, then the value is negative if neg: out -= (1 &lt;&lt; 24) print(hex(a), hex(b), hex(c), neg, out) return out twos_compliment([0x00, 0x00, 0x01]) &gt;&gt;&gt; 1 twos_compliment([0xff,0xff,0xff]) &gt;&gt;&gt; -1 twos_compliment([0b00010010, 0b11010110, 0b10000111]) &gt;&gt;&gt; 1234567 twos_compliment([0b11101101, 0b00101001, 0b01111001]) &gt;&gt;&gt; -1234567 twos_compliment([0b01110100, 0b11001011, 0b10110001]) &gt;&gt;&gt; 7654321 twos_compliment([0b10001011, 0b00110100, 0b01001111]) &gt;&gt;&gt; -7654321 </code></pre>
0
2016-06-29T00:51:41Z
[ "python", "bit-manipulation", "twos-complement" ]
Two's Complement in Python
1,604,464
<p>Is there a built in function in python which will convert a binary string, for example '111111111111', to the <a href="http://en.wikipedia.org/wiki/Two%27s_complement">two's complement integer</a> -1? </p>
28
2009-10-22T00:53:12Z
38,703,883
<p>It's much easier than all that...</p> <p>for X on N bits: Comp = (-X) &amp; (2**N - 1)</p> <pre><code>def twoComplement(number, nBits): return (-number) &amp; (2**nBits - 1) </code></pre>
0
2016-08-01T16:36:29Z
[ "python", "bit-manipulation", "twos-complement" ]
How to get output?
1,604,811
<p>I am using the Python/C API with my app and am wondering how you can get console output with a gui app. When there is a script error, it is displayed via printf but this obviously has no effect with a gui app. I want to be able to obtain the output without creating a console. Can this be done?</p> <p>Edit - Im using Windows, btw.</p> <p>Edit - The Python/C library internally calls printf and does so before any script can be loaded and run. If there is an error I want to be able to get it.</p>
0
2009-10-22T03:06:24Z
1,604,822
<p>Use the <a href="http://www.python.org/doc/2.5/lib/module-logging.html" rel="nofollow"><code>logging</code></a> package instead of printf. You can use something similar if you need to log output from a C function.</p>
1
2009-10-22T03:10:24Z
[ "python", "user-interface" ]
How to get output?
1,604,811
<p>I am using the Python/C API with my app and am wondering how you can get console output with a gui app. When there is a script error, it is displayed via printf but this obviously has no effect with a gui app. I want to be able to obtain the output without creating a console. Can this be done?</p> <p>Edit - Im using Windows, btw.</p> <p>Edit - The Python/C library internally calls printf and does so before any script can be loaded and run. If there is an error I want to be able to get it.</p>
0
2009-10-22T03:06:24Z
1,604,842
<p>If by <code>printf</code> you mean exactly thqt call from C code, you need to redirect (and un-buffer) your standard output (file descriptor 0) to somewhere you can pick up the data from -- far from trivial, esp. in Windows, although maybe doable. But why not just change that call in your C code to something more sensible? (Worst case, a <code>geprintf</code> function of your own devising that mimics printf to build a string then directs that string appropriately).</p> <p>If you actually mean <code>print</code> statements in Python code, it's much easier -- just set sys.stdout to an object with a <code>write</code> method accepting a string, and you can have that method do whatever you want, including logging, writing on a GUI windows, whatever you wish. Ah were it that simple at the C level!-)</p>
1
2009-10-22T03:16:37Z
[ "python", "user-interface" ]
Making a Windows .exe with gui2exe does not work because of missing MSVCP90.dll
1,605,006
<p>I'm trying to compile my python script into a single .exe using gui2exe (which uses py2exe to create a .exe). My program is using wxWidgets and everytime I try to compile it I get the following error message:</p> <blockquote> <p>error MSVCP90.dll: No such file or directory. </p> </blockquote> <p>I have already downloaded and installed the VC++ redistributable package, so I should have this .dll shouldn't I? </p>
9
2009-10-22T04:20:01Z
1,605,012
<p>Yes you should have it. You have to exclude it from py2exe.</p> <pre><code>options = { 'py2exe': { 'dll_excludes': [ 'MSVCP90.dll' ] } } setup(windows=["main.py"], options=options) </code></pre>
8
2009-10-22T04:21:42Z
[ "python", "dll", "wxwidgets", "py2exe", "gui2exe" ]
Making a Windows .exe with gui2exe does not work because of missing MSVCP90.dll
1,605,006
<p>I'm trying to compile my python script into a single .exe using gui2exe (which uses py2exe to create a .exe). My program is using wxWidgets and everytime I try to compile it I get the following error message:</p> <blockquote> <p>error MSVCP90.dll: No such file or directory. </p> </blockquote> <p>I have already downloaded and installed the VC++ redistributable package, so I should have this .dll shouldn't I? </p>
9
2009-10-22T04:20:01Z
5,768,777
<p>what you need is to go to microsoft's download site and get visual C++ 2008 redistributed package. Tell it to do a repair and search for the driver. Copy the driver to the DLL folder in the python directory</p>
1
2011-04-24T05:15:50Z
[ "python", "dll", "wxwidgets", "py2exe", "gui2exe" ]
What files do I need to include with my Python app?
1,605,022
<p>I have an app that uses the python/c api and I was wondering what files I need to distribute with it? The app runs on Windows and links with libpython31.a Are there any other files? I tried the app on a seperate Win2k system and it said that python31.dll was needed so theres at least one.</p> <p>Edit - My app is written in C++ and uses the Python/C api as noted below.</p>
2
2009-10-22T04:29:08Z
1,605,039
<p>The best way to tell is to try it on 'clean' installations of windows and see what it complains about. Virtual machines are a good way to do that.</p>
2
2009-10-22T04:36:50Z
[ "python", "file", "runtime" ]
What files do I need to include with my Python app?
1,605,022
<p>I have an app that uses the python/c api and I was wondering what files I need to distribute with it? The app runs on Windows and links with libpython31.a Are there any other files? I tried the app on a seperate Win2k system and it said that python31.dll was needed so theres at least one.</p> <p>Edit - My app is written in C++ and uses the Python/C api as noted below.</p>
2
2009-10-22T04:29:08Z
1,605,079
<p>You'll need at least Python's own DLL (release-specific) and the wincrt DLL version it requires, also Python version depended (if you want to run on releases of Windows that don't come with that DLL). The popular <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a>, the not-widely-know but hugely powerful <a href="http://www.pyinstaller.org/" rel="nofollow">Pyinstaller</a> (<strong>NOTE</strong>: use the svn version, <strong>not</strong> the released version which is aeons behind), and similar package-makers, do a good job of identifying and solving all such dependencies, so there's no case for doing it by hand!</p>
1
2009-10-22T04:54:39Z
[ "python", "file", "runtime" ]
python fileinput changes permission
1,605,288
<p>In my python code, I use the fileinput module for inplace replacing:</p> <pre><code>import fileinput for line in fileinput.FileInput("permission.txt",inplace=1): line = line.strip() if not 'def' in line: print line else: line=line.replace(line,'zzz') print line fileinput.close() </code></pre> <p>However, once it is done, permission.txt permissions is now changed to root only access. I can no longer edit the file. I can only delete it.</p> <p>I did some googling and it mentioned that this could be caused because fileinput creates a temporary file for this read/write replace interaction.</p> <p>However, I would have thought there would be a fix for this since the bug was reported in 1999. Is it something I have to do in my code to keep the permissions the same? or is it an operating system level issue.</p> <p>I'm using Python 2.6.2 on Ubuntu 9.04</p>
1
2009-10-22T06:05:50Z
1,605,340
<p>If you can help it, don't run your script as root.</p> <p><strong>EDIT</strong> Well, the answer has been accepted, but it's not really much of an answer. In case you must run the script as root (or indeed as any other user), you can use <a href="http://docs.python.org/library/os.html#os.stat" rel="nofollow"><code>os.stat()</code></a> to determine the user id and group id of the file's owner before processing the file, and then restore the file ownership after processing.</p> <pre><code>import fileinput import os # save original file ownership details stat = os.stat('permission.txt') uid, gid = stat[4], stat[5] for line in fileinput.FileInput("permission.txt",inplace=1): line = line.strip() if not 'def' in line: print line else: line=line.replace(line,'zzz') print line fileinput.close() # restore original file ownership os.chown("permission.txt", uid, gid) </code></pre>
0
2009-10-22T06:23:03Z
[ "python", "file-permissions", "file-io" ]
How can I grab the color of a pixel on my desktop? (Linux)
1,605,350
<p>I want to grab the color of a pixel with known coordinates on my Linux desktop.</p> <p>Until now, I've used <code>"import -window SomeWindow -crop 1x1+X+Y /tmp/grab.jpg"</code> then extracting the pixel value using Python and <a href="http://en.wikipedia.org/wiki/Python%5FImaging%5FLibrary">PIL</a>.</p> <p>This does the job, but since import grabs the whole window before cropping, it's very slow :(</p> <p>Are there any clever way to grab the color of only one pixel? I know both relative (window) and absolute coordinates. </p> <p>A Python or shell script would be preferable, but if you know some clever C/<a href="http://en.wikipedia.org/wiki/X%5FWindow%5FSystem">X11</a> functions, also please let me know :)</p>
7
2009-10-22T06:25:24Z
1,605,380
<p>This does the trick, but requires python-gtk:</p> <pre><code>import gtk.gdk import sys def PixelAt(x, y): w = gtk.gdk.get_default_root_window() sz = w.get_size() pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1]) pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1]) pixel_array = pb.get_pixels_array() return pixel_array[y][x] print PixelAt(int(sys.argv[1]), int(sys.argv[2])) </code></pre> <p>On Ubuntu 9.10, this also requires python-numpy or it segfaults the python interpreter on the <code>get_pixels_array</code> line. Ubuntu 10.04 it still has this requirement, or it causes an ImportError regarding numpy.core.multiarray.</p>
7
2009-10-22T06:37:29Z
[ "python", "linux", "shell", "imagemagick", "image" ]
How can I grab the color of a pixel on my desktop? (Linux)
1,605,350
<p>I want to grab the color of a pixel with known coordinates on my Linux desktop.</p> <p>Until now, I've used <code>"import -window SomeWindow -crop 1x1+X+Y /tmp/grab.jpg"</code> then extracting the pixel value using Python and <a href="http://en.wikipedia.org/wiki/Python%5FImaging%5FLibrary">PIL</a>.</p> <p>This does the job, but since import grabs the whole window before cropping, it's very slow :(</p> <p>Are there any clever way to grab the color of only one pixel? I know both relative (window) and absolute coordinates. </p> <p>A Python or shell script would be preferable, but if you know some clever C/<a href="http://en.wikipedia.org/wiki/X%5FWindow%5FSystem">X11</a> functions, also please let me know :)</p>
7
2009-10-22T06:25:24Z
1,605,631
<p>If you are using KDE4 there is a Color Picker Widget that you can add to either your panel or your Desktop. To add the widget either right click on the Desktop and choose add widget OR right click on the panel and choose Panel Options > Add Widgets </p>
1
2009-10-22T07:53:59Z
[ "python", "linux", "shell", "imagemagick", "image" ]
How can I grab the color of a pixel on my desktop? (Linux)
1,605,350
<p>I want to grab the color of a pixel with known coordinates on my Linux desktop.</p> <p>Until now, I've used <code>"import -window SomeWindow -crop 1x1+X+Y /tmp/grab.jpg"</code> then extracting the pixel value using Python and <a href="http://en.wikipedia.org/wiki/Python%5FImaging%5FLibrary">PIL</a>.</p> <p>This does the job, but since import grabs the whole window before cropping, it's very slow :(</p> <p>Are there any clever way to grab the color of only one pixel? I know both relative (window) and absolute coordinates. </p> <p>A Python or shell script would be preferable, but if you know some clever C/<a href="http://en.wikipedia.org/wiki/X%5FWindow%5FSystem">X11</a> functions, also please let me know :)</p>
7
2009-10-22T06:25:24Z
20,907,085
<p>Here is a much faster function based on <em>richq</em>'s <a href="http://stackoverflow.com/a/1605380">answer</a>.<br> This one reads only one pixel from the screen instead of getting a huge array of all the pixels.</p> <pre><code>import gtk.gdk def pixel_at(x, y): rw = gtk.gdk.get_default_root_window() pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 1, 1) pixbuf = pixbuf.get_from_drawable(rw, rw.get_colormap(), x, y, 0, 0, 1, 1) return tuple(pixbuf.pixel_array[0, 0]) </code></pre> <pre><code>&gt;&gt;&gt; pixel_at(25, 5) (143, 178, 237) </code></pre> <p>Requires PyGTK, of course...</p>
3
2014-01-03T15:29:46Z
[ "python", "linux", "shell", "imagemagick", "image" ]
How can I grab the color of a pixel on my desktop? (Linux)
1,605,350
<p>I want to grab the color of a pixel with known coordinates on my Linux desktop.</p> <p>Until now, I've used <code>"import -window SomeWindow -crop 1x1+X+Y /tmp/grab.jpg"</code> then extracting the pixel value using Python and <a href="http://en.wikipedia.org/wiki/Python%5FImaging%5FLibrary">PIL</a>.</p> <p>This does the job, but since import grabs the whole window before cropping, it's very slow :(</p> <p>Are there any clever way to grab the color of only one pixel? I know both relative (window) and absolute coordinates. </p> <p>A Python or shell script would be preferable, but if you know some clever C/<a href="http://en.wikipedia.org/wiki/X%5FWindow%5FSystem">X11</a> functions, also please let me know :)</p>
7
2009-10-22T06:25:24Z
27,406,714
<p>Using gi.repository Gdk, it's even smaller and works on either Python 2 or 3:</p> <pre><code>#!/usr/bin/python3 # Print RGB color values of screen pixel at location x, y from gi.repository import Gdk import sys def PixelAt(x, y): w = Gdk.get_default_root_window() pb = Gdk.pixbuf_get_from_window(w, x, y, 1, 1) return pb.get_pixels() print(tuple(PixelAt(int(sys.argv[1]), int(sys.argv[2])))) </code></pre>
1
2014-12-10T17:01:34Z
[ "python", "linux", "shell", "imagemagick", "image" ]
django syncdb and an updated model
1,605,662
<p>I have recently updated my model, added a BooleanField to it however when I do <code>python manage.py syncdb</code>, it doesn't add the new field to the database for the model. How can I fix this ?</p>
83
2009-10-22T08:04:52Z
1,605,670
<p>Havent used django in a while, but i seem to remember that syncdb does perform alter commands on db tables. you have to drop the table then run again and it will create again.</p> <p>edit: sorry does NOT perform alter.</p>
2
2009-10-22T08:08:24Z
[ "python", "django", "django-models" ]
django syncdb and an updated model
1,605,662
<p>I have recently updated my model, added a BooleanField to it however when I do <code>python manage.py syncdb</code>, it doesn't add the new field to the database for the model. How can I fix this ?</p>
83
2009-10-22T08:04:52Z
1,605,673
<h2>From Django 1.7 onwards</h2> <p>Django has built in support for migrations - take a look at <a href="https://docs.djangoproject.com/en/dev/topics/migrations/">the documentation</a>.</p> <h2>For Django 1.6 and earlier</h2> <p>Django doesn't support migrations out of the box. There is a pluggable app for Django that does exactly that though, and it works great. It's called <a href="http://south.aeracode.org">South</a>.</p>
99
2009-10-22T08:09:17Z
[ "python", "django", "django-models" ]
django syncdb and an updated model
1,605,662
<p>I have recently updated my model, added a BooleanField to it however when I do <code>python manage.py syncdb</code>, it doesn't add the new field to the database for the model. How can I fix this ?</p>
83
2009-10-22T08:04:52Z
1,605,680
<p>Django currently does not do this automatically. Your options are:</p> <ol> <li>Drop the table from the database, then recreate it in new form using syncdb.</li> <li>Print out SQL for the database using <code>python manage.py sql (appname)</code>, find the added line for the field and add it manually using <code>alter table</code> SQL command. (This will also allow you to choose values of the field for your current records.)</li> <li>Use <a href="http://south.aeracode.org/">South</a> (per <a href="http://stackoverflow.com/questions/1605662/django-syncdb-and-an-updated-model/1605673#1605673">Dominic's answer</a>).</li> </ol>
13
2009-10-22T08:11:31Z
[ "python", "django", "django-models" ]
django syncdb and an updated model
1,605,662
<p>I have recently updated my model, added a BooleanField to it however when I do <code>python manage.py syncdb</code>, it doesn't add the new field to the database for the model. How can I fix this ?</p>
83
2009-10-22T08:04:52Z
1,605,694
<p>Follow these steps:</p> <ol> <li>Export your data to a fixture using the <a href="http://docs.djangoproject.com/en/dev/ref/django-admin/?from=olddocs#dumpdata">dumpdata</a> management command</li> <li>Drop the table</li> <li>Run syncdb</li> <li>Reload your data from the fixture using the <a href="http://docs.djangoproject.com/en/dev/ref/django-admin/?from=olddocs#loaddata-fixture-fixture">loaddata</a> management command</li> </ol>
11
2009-10-22T08:15:01Z
[ "python", "django", "django-models" ]
django syncdb and an updated model
1,605,662
<p>I have recently updated my model, added a BooleanField to it however when I do <code>python manage.py syncdb</code>, it doesn't add the new field to the database for the model. How can I fix this ?</p>
83
2009-10-22T08:04:52Z
6,127,375
<p>As suggested in top answer, I tried using <a href="http://south.aeracode.org/">South</a>, and after an hour of frustration with <a href="http://stackoverflow.com/questions/4840102/how-come-my-south-migrations-doesnt-work-for-django">obscure migration errors</a> decided to go with <a href="http://code.google.com/p/django-evolution/">Django Evolution</a> instead.</p> <p>I think it's easier to get started with than South, and it worked perfectly the first time I typed <code>./manage.py evolve --hint --execute</code>, so I'm happy with it.</p>
8
2011-05-25T15:57:56Z
[ "python", "django", "django-models" ]
django syncdb and an updated model
1,605,662
<p>I have recently updated my model, added a BooleanField to it however when I do <code>python manage.py syncdb</code>, it doesn't add the new field to the database for the model. How can I fix this ?</p>
83
2009-10-22T08:04:52Z
27,652,020
<p>If you run Django with Apache and MySQL, restart apache after making migration with <em>makemigrations</em>.</p>
0
2014-12-26T01:22:51Z
[ "python", "django", "django-models" ]
django syncdb and an updated model
1,605,662
<p>I have recently updated my model, added a BooleanField to it however when I do <code>python manage.py syncdb</code>, it doesn't add the new field to the database for the model. How can I fix this ?</p>
83
2009-10-22T08:04:52Z
37,202,110
<p>In django <strong>1.6</strong></p> <ul> <li><p>At first we have run - <code>python manage.py sql &lt;app name&gt;</code></p></li> <li><p>Then we have to run - <code>python manage.py syncdb</code></p></li> </ul>
0
2016-05-13T05:49:54Z
[ "python", "django", "django-models" ]
Django: How to detect if translation is activated?
1,605,706
<p><code>django.utils.translation.get_language()</code> returns default locale if translation is not activated. Is there a way to find out whether the translation is activated (via <code>translation.activate()</code>) or not?</p>
2
2009-10-22T08:18:24Z
1,696,958
<p>Always inspect source code for such question, it's faster than posting to Web!</p> <p>Django does it's black magic behind the scene, and uses some kind of dispatcher to simulate disabled translations.</p> <p>The best way for you to do is:</p> <pre><code>import setttings assert settings.USE_i18N == True </code></pre>
-2
2009-11-08T15:59:48Z
[ "python", "django", "internationalization" ]
Django: How to detect if translation is activated?
1,605,706
<p><code>django.utils.translation.get_language()</code> returns default locale if translation is not activated. Is there a way to find out whether the translation is activated (via <code>translation.activate()</code>) or not?</p>
2
2009-10-22T08:18:24Z
2,450,201
<p>Horribly hacky, but should work in at least 1.1.1:</p> <pre><code>import django.utils.translation.trans_real as trans from django.utils.thread_support import currentThread def isactive(): return currentThread() in trans._active </code></pre>
2
2010-03-15T20:22:18Z
[ "python", "django", "internationalization" ]
Django: How to detect if translation is activated?
1,605,706
<p><code>django.utils.translation.get_language()</code> returns default locale if translation is not activated. Is there a way to find out whether the translation is activated (via <code>translation.activate()</code>) or not?</p>
2
2009-10-22T08:18:24Z
2,450,262
<p>Depends on application and architecture...</p> <p>Hack provided by Ignacio should works, but what is you will run in non activated yet thread?</p> <p>I would use Ignacio solution + add Queue visible by all threads, monkeypatch trans_real.activate function and set attribute in queue.</p>
0
2010-03-15T20:31:13Z
[ "python", "django", "internationalization" ]
How to modify the Python 'default' dictionary so that it always returns a default value
1,605,750
<p>I'm using all of them to print the names of assigned IANA values in a packet. So all of the dictionaries have the same default value "RESERVED". </p> <p>I don't want to use <code>d.get(key,default)</code> but access dictionaries by <code>d[key]</code> so that if the key is not in d, it returns the default (that is same for all dictionaries).</p> <p>I do not necessarily need to use dictionaries, but they were the intuitive choice... Also, a dictionary where I could do this</p> <pre><code>d = { 1..16 = "RESERVED", 17 : "Foo", 18 : "Bar, 19..255: "INVALID" } </code></pre> <p>Would be the preferred solution</p> <p>Tuples could be another alternative, but then I'm prone to offset errors assigning the values... (and my code would not be "human readable")</p> <p>Oh yeah, Python 2.4</p>
3
2009-10-22T08:27:22Z
1,605,802
<p>If you can migrate to Python 2.5, there is the <em>defaultdict</em> class, as shown <a href="http://docs.python.org/library/collections.html#collections.defaultdict">here</a>. You can pass it an initializer that returns what you want. Otherwise, you'll have to roll your own implementation of it, I fear.</p>
9
2009-10-22T08:37:59Z
[ "python", "dictionary", "python-2.4" ]
How to modify the Python 'default' dictionary so that it always returns a default value
1,605,750
<p>I'm using all of them to print the names of assigned IANA values in a packet. So all of the dictionaries have the same default value "RESERVED". </p> <p>I don't want to use <code>d.get(key,default)</code> but access dictionaries by <code>d[key]</code> so that if the key is not in d, it returns the default (that is same for all dictionaries).</p> <p>I do not necessarily need to use dictionaries, but they were the intuitive choice... Also, a dictionary where I could do this</p> <pre><code>d = { 1..16 = "RESERVED", 17 : "Foo", 18 : "Bar, 19..255: "INVALID" } </code></pre> <p>Would be the preferred solution</p> <p>Tuples could be another alternative, but then I'm prone to offset errors assigning the values... (and my code would not be "human readable")</p> <p>Oh yeah, Python 2.4</p>
3
2009-10-22T08:27:22Z
1,605,909
<p>If you can, use <a href="http://stackoverflow.com/questions/1605750/how-to-modify-the-python-default-dictionary-so-that-it-always-returns-a-default/1605802#1605802">Mario's solution</a>. </p> <p>If you can't, you just have to subclass a dictionary-like object. Now, you can do that by inheriting directly from "dict", it will be fast and efficient. For old Python versions, with which you can't inherit from "dict", there is "UserDict", a pure Python dictionary implementation.</p> <p>With it, you would do it this way :</p> <pre><code>#!/usr/bin/env python # -*- coding= UTF-8 -*- import UserDict class DefaultDict(UserDict.UserDict) : default_value = 'RESERVED' def __getitem__(self, key) : return self.data.get(key, DefaultDict.default_value) d = DefaultDict() d["yes"] = True; print d["yes"] print d["no"] </code></pre> <p>Keep in mind that "UserDict" is slower than "dict". </p>
4
2009-10-22T09:00:38Z
[ "python", "dictionary", "python-2.4" ]
How to modify the Python 'default' dictionary so that it always returns a default value
1,605,750
<p>I'm using all of them to print the names of assigned IANA values in a packet. So all of the dictionaries have the same default value "RESERVED". </p> <p>I don't want to use <code>d.get(key,default)</code> but access dictionaries by <code>d[key]</code> so that if the key is not in d, it returns the default (that is same for all dictionaries).</p> <p>I do not necessarily need to use dictionaries, but they were the intuitive choice... Also, a dictionary where I could do this</p> <pre><code>d = { 1..16 = "RESERVED", 17 : "Foo", 18 : "Bar, 19..255: "INVALID" } </code></pre> <p>Would be the preferred solution</p> <p>Tuples could be another alternative, but then I'm prone to offset errors assigning the values... (and my code would not be "human readable")</p> <p>Oh yeah, Python 2.4</p>
3
2009-10-22T08:27:22Z
23,388,871
<p>You can use the following class (tested in Python 2.7) Just change zero to any default value you like.</p> <pre><code>class cDefaultDict(dict): # dictionary that returns zero for missing keys # keys with zero values are not stored def __missing__(self,key): return 0 def __setitem__(self, key, value): if value==0: if key in self: # returns zero anyway, so no need to store it del self[key] else: dict.__setitem__(self, key, value) </code></pre>
0
2014-04-30T13:03:33Z
[ "python", "dictionary", "python-2.4" ]
Pythonic way to print a table
1,605,861
<p>I'm using this simple function:</p> <pre><code>def print_players(players): tot = 1 for p in players: print '%2d: %15s \t (%d|%d) \t was: %s' % (tot, p['nick'], p['x'], p['y'], p['oldnick']) tot += 1 </code></pre> <p>and I'm supposing nicks are no longer than 15 characters.<br /> I'd like to keep each "column" aligned, is there a some syntactic sugar allowing me to do the same but keeping the nicknames column left-aligned instead of right-aligned, without breaking column on the right?</p> <p>The equivalent, uglier, code would be:</p> <pre><code>def print_players(players): tot = 1 for p in players: print '%2d: %s \t (%d|%d) \t was: %s' % (tot, p['nick']+' '*(15-len(p['nick'])), p['x'], p['y'], p['oldnick']) tot += 1 </code></pre> <p>Thanks to all, here is the final version:</p> <pre><code>def print_players(players): for tot, p in enumerate(players, start=1): print '%2d:'%tot, '%(nick)-12s (%(x)d|%(y)d) \t was %(oldnick)s'%p </code></pre>
1
2009-10-22T08:48:48Z
1,605,869
<p>To left-align instead of right-align, use <code>%-15s</code> instead of <code>%15s</code>.</p>
4
2009-10-22T08:51:24Z
[ "printing", "python", "string-formatting" ]
Pythonic way to print a table
1,605,861
<p>I'm using this simple function:</p> <pre><code>def print_players(players): tot = 1 for p in players: print '%2d: %15s \t (%d|%d) \t was: %s' % (tot, p['nick'], p['x'], p['y'], p['oldnick']) tot += 1 </code></pre> <p>and I'm supposing nicks are no longer than 15 characters.<br /> I'd like to keep each "column" aligned, is there a some syntactic sugar allowing me to do the same but keeping the nicknames column left-aligned instead of right-aligned, without breaking column on the right?</p> <p>The equivalent, uglier, code would be:</p> <pre><code>def print_players(players): tot = 1 for p in players: print '%2d: %s \t (%d|%d) \t was: %s' % (tot, p['nick']+' '*(15-len(p['nick'])), p['x'], p['y'], p['oldnick']) tot += 1 </code></pre> <p>Thanks to all, here is the final version:</p> <pre><code>def print_players(players): for tot, p in enumerate(players, start=1): print '%2d:'%tot, '%(nick)-12s (%(x)d|%(y)d) \t was %(oldnick)s'%p </code></pre>
1
2009-10-22T08:48:48Z
1,605,950
<p>Seeing that <code>p</code> seems to be a dict, how about:</p> <pre><code>print '%2d' % tot + ': %(nick)-15s \t (%(x)d|%(y)d) \t was: %(oldnick)15s' % p </code></pre>
2
2009-10-22T09:08:09Z
[ "printing", "python", "string-formatting" ]
Pythonic way to print a table
1,605,861
<p>I'm using this simple function:</p> <pre><code>def print_players(players): tot = 1 for p in players: print '%2d: %15s \t (%d|%d) \t was: %s' % (tot, p['nick'], p['x'], p['y'], p['oldnick']) tot += 1 </code></pre> <p>and I'm supposing nicks are no longer than 15 characters.<br /> I'd like to keep each "column" aligned, is there a some syntactic sugar allowing me to do the same but keeping the nicknames column left-aligned instead of right-aligned, without breaking column on the right?</p> <p>The equivalent, uglier, code would be:</p> <pre><code>def print_players(players): tot = 1 for p in players: print '%2d: %s \t (%d|%d) \t was: %s' % (tot, p['nick']+' '*(15-len(p['nick'])), p['x'], p['y'], p['oldnick']) tot += 1 </code></pre> <p>Thanks to all, here is the final version:</p> <pre><code>def print_players(players): for tot, p in enumerate(players, start=1): print '%2d:'%tot, '%(nick)-12s (%(x)d|%(y)d) \t was %(oldnick)s'%p </code></pre>
1
2009-10-22T08:48:48Z
1,605,963
<p>Or if your using python 2.6 you can use the <a href="http://docs.python.org/library/string.html?#string-formatting" rel="nofollow">format</a> method of the string:</p> <p>This defines a dictionary of values, and uses them for dipslay:</p> <pre><code>&gt;&gt;&gt; values = {'total':93, 'name':'john', 'x':33, 'y':993, 'oldname':'rodger'} &gt;&gt;&gt; '{total:2}: {name:15} \t ({x}|{y}\t was: {oldname}'.format(**values) '93: john \t (33|993\t was: rodger' </code></pre>
3
2009-10-22T09:11:29Z
[ "printing", "python", "string-formatting" ]
Pythonic way to print a table
1,605,861
<p>I'm using this simple function:</p> <pre><code>def print_players(players): tot = 1 for p in players: print '%2d: %15s \t (%d|%d) \t was: %s' % (tot, p['nick'], p['x'], p['y'], p['oldnick']) tot += 1 </code></pre> <p>and I'm supposing nicks are no longer than 15 characters.<br /> I'd like to keep each "column" aligned, is there a some syntactic sugar allowing me to do the same but keeping the nicknames column left-aligned instead of right-aligned, without breaking column on the right?</p> <p>The equivalent, uglier, code would be:</p> <pre><code>def print_players(players): tot = 1 for p in players: print '%2d: %s \t (%d|%d) \t was: %s' % (tot, p['nick']+' '*(15-len(p['nick'])), p['x'], p['y'], p['oldnick']) tot += 1 </code></pre> <p>Thanks to all, here is the final version:</p> <pre><code>def print_players(players): for tot, p in enumerate(players, start=1): print '%2d:'%tot, '%(nick)-12s (%(x)d|%(y)d) \t was %(oldnick)s'%p </code></pre>
1
2009-10-22T08:48:48Z
1,605,974
<p>Slightly off topic, but you can avoid performing explicit addition on <code>tot</code> using <a href="http://docs.python.org/3.1/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a>:</p> <pre><code>for tot, p in enumerate(players, start=1): print '...' </code></pre>
4
2009-10-22T09:13:05Z
[ "printing", "python", "string-formatting" ]
What is the best way to store integers mapped to strings so that the keys can be ranges in python?
1,606,150
<p>What would be the best way to store (non-mutable) data that is of format:</p> <pre><code>doodahs = { 0-256: "FOO", 257: "BAR", 258: "FISH", 279: "MOOSE", 280-65534: "Darth Vader", 65535: "Death to all newbies" } </code></pre> <p>I have a relatively large amount of these type of data sets, so something that I can define the way of dictionaries (or close to it) and access via indexes.</p> <p>Oh, and this is on Python 2.4, so please give really really good reason for upgrade if you want me to use a newer version (and I'll go for 3 :)</p>
1
2009-10-22T09:50:15Z
1,606,215
<p>I'd split the range into a tuple and then inside your class, keep the items in an ordered list. You can use the <a href="http://docs.python.org/library/bisect.html" rel="nofollow">bisect</a> module to make inserts O(n) and lookup O(logn).</p> <p>If you are converting a dict to your new class, you can build an unordered list and sort it at the end</p> <pre><code>doodahs = [ (0, 256, "FOO"), (257, 257, "BAR"), (258, 258, "FISH"), (279, 279, "MOOSE"), (280, 65534, "Darth Vader"), (65535, 65535, "Death to all newbies")] </code></pre> <p>Your <code>__getitem__</code> might work something like this:</p> <pre><code>def __getitem__(self, key): return self.doodahs[bisect.bisect(self.doodahs, (key,))] </code></pre> <p><code>__setitem__</code> might be something like this:</p> <pre><code>def __setitem__(self,range,value): bisect.insort(self.doodahs, range+(value,)) </code></pre>
5
2009-10-22T10:03:09Z
[ "python", "types" ]
What is the best way to store integers mapped to strings so that the keys can be ranges in python?
1,606,150
<p>What would be the best way to store (non-mutable) data that is of format:</p> <pre><code>doodahs = { 0-256: "FOO", 257: "BAR", 258: "FISH", 279: "MOOSE", 280-65534: "Darth Vader", 65535: "Death to all newbies" } </code></pre> <p>I have a relatively large amount of these type of data sets, so something that I can define the way of dictionaries (or close to it) and access via indexes.</p> <p>Oh, and this is on Python 2.4, so please give really really good reason for upgrade if you want me to use a newer version (and I'll go for 3 :)</p>
1
2009-10-22T09:50:15Z
1,606,305
<p>If your integers have an upper bound that's less than a few million, then you simply expand the ranges into individual values.</p> <pre><code>class RangedDict( dict ): def addRange( self, iterator, value ): for k in iterator: self[k]= value d= RangedDict() d.addRange( xrange(0,257), "FOO" ) d[257]= "BAR" d[258]= "FISH" d[279]= "MOOSE" d.addRange( xrange(280,65535), "Darth Vader" ) d[65535]= "Death to all newbies" </code></pre> <p>All your lookups work, and are instant.</p>
2
2009-10-22T10:24:09Z
[ "python", "types" ]
What is the best way to store integers mapped to strings so that the keys can be ranges in python?
1,606,150
<p>What would be the best way to store (non-mutable) data that is of format:</p> <pre><code>doodahs = { 0-256: "FOO", 257: "BAR", 258: "FISH", 279: "MOOSE", 280-65534: "Darth Vader", 65535: "Death to all newbies" } </code></pre> <p>I have a relatively large amount of these type of data sets, so something that I can define the way of dictionaries (or close to it) and access via indexes.</p> <p>Oh, and this is on Python 2.4, so please give really really good reason for upgrade if you want me to use a newer version (and I'll go for 3 :)</p>
1
2009-10-22T09:50:15Z
1,606,333
<pre><code>class dict2(dict): def __init__(self,obj): dict.__init__(self,obj) def __getitem__(self,key): if self.has_key(key): return super(dict2,self).__getitem__(key) else: for k in self: if '-' in k: [x,y] = str(k).split('-') if key in range(int(x),int(y)+1): return super(dict2,self).__getitem__(k) return None d = {"0-10":"HELLO"} d2 = dict2(d) print d,d2,d2["0-10"], d2[1] </code></pre>
0
2009-10-22T10:30:21Z
[ "python", "types" ]
What is the best way to store integers mapped to strings so that the keys can be ranges in python?
1,606,150
<p>What would be the best way to store (non-mutable) data that is of format:</p> <pre><code>doodahs = { 0-256: "FOO", 257: "BAR", 258: "FISH", 279: "MOOSE", 280-65534: "Darth Vader", 65535: "Death to all newbies" } </code></pre> <p>I have a relatively large amount of these type of data sets, so something that I can define the way of dictionaries (or close to it) and access via indexes.</p> <p>Oh, and this is on Python 2.4, so please give really really good reason for upgrade if you want me to use a newer version (and I'll go for 3 :)</p>
1
2009-10-22T09:50:15Z
1,606,561
<p>Given that you don't have any "gaps" in your keys, why you just don't store the beginning of each segment and then lookup with bisect like suggested?</p> <pre><code>doodahs = ( (0, "FOO"), (257, "BAR"), (258, "FISH"), (279, "MOOSE"), (280, "Darth Vader"), (65535, "Death to all newbies") ) </code></pre>
1
2009-10-22T11:24:08Z
[ "python", "types" ]
How can I make HTML safe for web browser with python?
1,606,201
<p>How can I make HTML from email safe to display in web browser with python?</p> <p>Any external references shouldn't be followed when displayed. In other words, all displayed content should come from the email and nothing from internet.</p> <p>Other than spam emails should be displayed as closely as possible like intended by the writer.</p> <p>I would like to avoid coding this myself.</p> <p>Solutions requiring latest browser (firefox) version are also acceptable.</p>
1
2009-10-22T10:00:21Z
1,606,315
<p>Use the HTMLparser module, or install BeautifulSoup, and use those to parse the HTML and disable or remove the tags. This will leave whatever link text was there, but it will not be highlighted and it will not be clickable, since you are displaying it with a web browser component.</p> <p>You could make it clearer what was done by replacing the <code>&lt;A&gt;&lt;/A&gt;</code> with a <code>&lt;SPAN&gt;&lt;/SPAN&gt;</code> and changing the text decoration to show where the link used to be. Maybe a different shade of blue than normal and a dashed underscore to indicate brokenness. That way you are a little closer to displaying it as intended without actually misleading people into clicking on something that is not clickable. You could even add a hover in <a href="http://www.dyn-web.com/code/tooltips/" rel="nofollow">Javascript</a> or <a href="http://psacake.com/web/jl.asp" rel="nofollow">pure CSS</a> that pops up a tooltip explaining that links have been disabled for security reasons.</p> <p>Similar things could be done with <code>&lt;IMG&gt;&lt;/IMG&gt;</code> tags including replacing them with a blank rectangle to ensure that the page layout is close to the original. </p> <p>I've done stuff like this with <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>, but HTMLparser is included with Python. In older Python distribs, there was an htmllib which is now deprecated. Since the HTML in an email message might not be fully correct, use Beautiful Soup 3.0.7a which is better at making sense of broken HTML.</p>
0
2009-10-22T10:25:27Z
[ "python", "html", "email", "browser", "html-sanitizing" ]
How can I make HTML safe for web browser with python?
1,606,201
<p>How can I make HTML from email safe to display in web browser with python?</p> <p>Any external references shouldn't be followed when displayed. In other words, all displayed content should come from the email and nothing from internet.</p> <p>Other than spam emails should be displayed as closely as possible like intended by the writer.</p> <p>I would like to avoid coding this myself.</p> <p>Solutions requiring latest browser (firefox) version are also acceptable.</p>
1
2009-10-22T10:00:21Z
1,611,676
<p><a href="http://code.google.com/p/html5lib/" rel="nofollow">html5lib</a> contains an HTML+CSS sanitizer. It allows too much currently, but it shouldn't be too hard to modify it to match the use case.</p> <p>Found it from <a href="http://jacobian.org/writing/untrusted-users-and-html/" rel="nofollow">here</a>.</p>
1
2009-10-23T06:26:45Z
[ "python", "html", "email", "browser", "html-sanitizing" ]
How can I make HTML safe for web browser with python?
1,606,201
<p>How can I make HTML from email safe to display in web browser with python?</p> <p>Any external references shouldn't be followed when displayed. In other words, all displayed content should come from the email and nothing from internet.</p> <p>Other than spam emails should be displayed as closely as possible like intended by the writer.</p> <p>I would like to avoid coding this myself.</p> <p>Solutions requiring latest browser (firefox) version are also acceptable.</p>
1
2009-10-22T10:00:21Z
1,611,820
<p>I'm not quite clear with what exactly you mean with "safe". It's a pretty big topic... but, for what it's worth:</p> <p>In my opinion, the <a href="http://code.activestate.com/recipes/52281/" rel="nofollow">stripping parser</a> from the ActiveState Cookbook is one of the easiest solutions. You can pretty much copy/paste the class and start using it.</p> <p>Have a look at the comments as well. The last one states that it doesn't work anymore, but I also have this running in an application somewhere and it works fine. From work, I don't have access to that box, so I'll have to look it up over the weekend.</p>
1
2009-10-23T07:10:04Z
[ "python", "html", "email", "browser", "html-sanitizing" ]
Using multiple databases with Elixir
1,606,341
<p>I would like to provide database for my program that uses elixir for ORM. Right now the database file (I am using SQLite) must be hardcoded in metadata, but I would like to be able to pass this in argv. Is there any way to do this nice?</p> <p>The only thing I thought of is to:</p> <pre><code>from sys import argv metadata.bind = argv[1] </code></pre> <p>Can I set this in the main script and it would be used in all modules, that define any Entities?</p>
1
2009-10-22T10:32:18Z
1,606,389
<p>Your question seems to be more related to general argument parsing in python than with elixir.</p> <p>Anyway, I had a similar problem, and I have solved it by using different configuration files and parsing them with the <a href="http://docs.python.org/library/configparser.html" rel="nofollow">configparse</a> module in python.</p> <p>For example, I have two config files, and each of them describes the db url, username, password, etc.. of one database. When I want to switch to another configuration, I pass an option like --configfile guest to the script (I use <a href="http://code.google.com/p/argparse/" rel="nofollow">argparse</a> for the command line interface), then the script looks for a config file called guest.txt, and reads all the information there.</p> <p>This is a lot safer, because if you pass a metadata string as a command line argument you can have some security issues, and moreover it is a lot longer to type.</p> <p>By the way, you can also find useful to write a Makefile to store the most common options.</p> <p>e.g. cat >Makefile</p> <pre><code>debug_db: ipython connect_db.py -config guest -i connect_root: ipython connect_db.py -config db1_root -i connect_db1: ipython connect_db.py -config db1 -i </code></pre> <p>and on the command line, you only have to type 'make debug_db' or 'make connect_db1' to execute a rule.</p>
0
2009-10-22T10:44:38Z
[ "python", "python-elixir" ]
Using multiple databases with Elixir
1,606,341
<p>I would like to provide database for my program that uses elixir for ORM. Right now the database file (I am using SQLite) must be hardcoded in metadata, but I would like to be able to pass this in argv. Is there any way to do this nice?</p> <p>The only thing I thought of is to:</p> <pre><code>from sys import argv metadata.bind = argv[1] </code></pre> <p>Can I set this in the main script and it would be used in all modules, that define any Entities?</p>
1
2009-10-22T10:32:18Z
1,606,391
<p>I have some code that does this in a slightly nicer fashion than just using argv</p> <pre><code>from optparse import OptionParser parser = OptionParser() parser.add_option("-u", "--user", dest="user", help="Database username") parser.add_option("-p", "--password", dest="password", help="Database password") parser.add_option("-D", "--database", dest="database", default="myDatabase", help="Database name") parser.add_option("-e", "--engine", dest="engine", default="mysql", help="Database engine") parser.add_option("-H", "--host", dest="host", default="localhost", help="Database host") (options, args) = parser.parse_args() def opt_hash(name): global options return getattr(options, name) options.__getitem__ = opt_hash metadata.bind = '%(engine)s://%(user)s:%(password)s@%(host)s/%(database)s' % options </code></pre> <p>Note that the part using opt_hash is a bit of a hack. I use it because OptionParser doesn't return a normal hash, which is what is really needed for the niceness of the bind string I use in the last line.</p>
1
2009-10-22T10:45:30Z
[ "python", "python-elixir" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) print Point.__doc__ # -&gt; "Point(x, y)" print Point2.__doc__ # -&gt; "Point2(x, y)" </code></pre> <p>but that doesn't cut it. Is it possible to do in some other way?</p>
39
2009-10-22T10:55:53Z
1,606,448
<p>No, you can only add doc strings to modules, classes and function (including methods)</p>
-1
2009-10-22T10:58:34Z
[ "python", "docstring", "namedtuple" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) print Point.__doc__ # -&gt; "Point(x, y)" print Point2.__doc__ # -&gt; "Point2(x, y)" </code></pre> <p>but that doesn't cut it. Is it possible to do in some other way?</p>
39
2009-10-22T10:55:53Z
1,606,478
<p>You can achieve this by creating a simple, empty wrapper class around the returned value from <code>namedtuple</code>. Contents of a file I created (<code>nt.py</code>):</p> <pre><code>from collections import namedtuple Point_ = namedtuple("Point", ["x", "y"]) class Point(Point_): """ A point in 2d space """ pass </code></pre> <p>Then in the Python REPL:</p> <pre><code>&gt;&gt;&gt; print nt.Point.__doc__ A point in 2d space </code></pre> <p>Or you could do:</p> <pre><code>&gt;&gt;&gt; help(nt.Point) # which outputs... </code></pre> <pre> Help on class Point in module nt: class Point(Point) | A point in 2d space | | Method resolution order: | Point | Point | __builtin__.tuple | __builtin__.object ... </pre> <p>If you don't like doing that by hand every time, it's trivial to write a sort-of factory function to do this:</p> <pre><code>def NamedTupleWithDocstring(docstring, *ntargs): nt = namedtuple(*ntargs) class NT(nt): __doc__ = docstring return NT Point3D = NamedTupleWithDocstring("A point in 3d space", "Point3d", ["x", "y", "z"]) p3 = Point3D(1,2,3) print p3.__doc__ </code></pre> <p>which outputs:</p> <pre><code>A point in 3d space </code></pre>
31
2009-10-22T11:03:35Z
[ "python", "docstring", "namedtuple" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) print Point.__doc__ # -&gt; "Point(x, y)" print Point2.__doc__ # -&gt; "Point2(x, y)" </code></pre> <p>but that doesn't cut it. Is it possible to do in some other way?</p>
39
2009-10-22T10:55:53Z
3,349,937
<p>You could concoct your own version of the <a href="http://code.activestate.com/recipes/500261" rel="nofollow"><strong>namedtuple factory function</strong></a> by Raymond Hettinger and add an optional <code>docstring</code> argument.&nbsp;&nbsp;However it would be easier -- and arguably better -- to just define your own factory function using the same basic technique as in the recipe.&nbsp;&nbsp;Either way, you'll end up with something reusable.</p> <pre><code>from collections import namedtuple def my_namedtuple(typename, field_names, verbose=False, rename=False, docstring=''): '''Returns a new subclass of namedtuple with the supplied docstring appended to the default one. &gt;&gt;&gt; Point = my_namedtuple('Point', 'x, y', docstring='A point in 2D space') &gt;&gt;&gt; print Point.__doc__ Point(x, y): A point in 2D space ''' # create a base class and concatenate its docstring and the one passed _base = namedtuple(typename, field_names, verbose, rename) _docstring = ''.join([_base.__doc__, ': ', docstring]) # fill in template to create a no-op subclass with the combined docstring template = '''class subclass(_base): %(_docstring)r pass\n''' % locals() # execute code string in a temporary namespace namespace = dict(_base=_base, _docstring=_docstring) try: exec template in namespace except SyntaxError, e: raise SyntaxError(e.message + ':\n' + template) return namespace['subclass'] # subclass object created </code></pre>
0
2010-07-28T04:23:11Z
[ "python", "docstring", "namedtuple" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) print Point.__doc__ # -&gt; "Point(x, y)" print Point2.__doc__ # -&gt; "Point2(x, y)" </code></pre> <p>but that doesn't cut it. Is it possible to do in some other way?</p>
39
2009-10-22T10:55:53Z
15,667,772
<p>Came across this old question via Google while wondering the same thing.</p> <p>Just wanted to point out that you can tidy it up even more by calling namedtuple() right from the class declaration:</p> <pre><code>from collections import namedtuple class Point(namedtuple('Point', 'x y')): """Here is the docstring.""" </code></pre>
34
2013-03-27T19:30:28Z
[ "python", "docstring", "namedtuple" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) print Point.__doc__ # -&gt; "Point(x, y)" print Point2.__doc__ # -&gt; "Point2(x, y)" </code></pre> <p>but that doesn't cut it. Is it possible to do in some other way?</p>
39
2009-10-22T10:55:53Z
20,388,499
<p>In Python 3, no wrapper is needed, as the <code>__doc__</code> attributes of types is writable.</p> <pre><code>from collections import namedtuple Point = namedtuple('Point', 'x y') Point.__doc__ = '''\ A 2-dimensional coordinate x - the abscissa y - the ordinate''' </code></pre> <p>This closely corresponds to a standard class definition, where the docstring follows the header.</p> <pre><code>class Point(): '''A 2-dimensional coordinate x - the abscissa y - the ordinate''' &lt;class code&gt; </code></pre> <p>This does not work in Python 2.</p> <p><code>AttributeError: attribute '__doc__' of 'type' objects is not writable</code>. </p>
30
2013-12-04T23:43:06Z
[ "python", "docstring", "namedtuple" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) print Point.__doc__ # -&gt; "Point(x, y)" print Point2.__doc__ # -&gt; "Point2(x, y)" </code></pre> <p>but that doesn't cut it. Is it possible to do in some other way?</p>
39
2009-10-22T10:55:53Z
26,017,342
<p>No need to use a wrapper class as suggested by the accepted answer. Simply literally <strong>add</strong> a docstring:</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) Point.__doc__="A point in 2D space" </code></pre> <p>This results in: (example using <code>ipython3</code>):</p> <pre><code>In [1]: Point? Type: type String Form:&lt;class '__main__.Point'&gt; Docstring: A point in 2D space In [2]: </code></pre> <p><em>Voilà!</em></p>
2
2014-09-24T12:48:47Z
[ "python", "docstring", "namedtuple" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) print Point.__doc__ # -&gt; "Point(x, y)" print Point2.__doc__ # -&gt; "Point2(x, y)" </code></pre> <p>but that doesn't cut it. Is it possible to do in some other way?</p>
39
2009-10-22T10:55:53Z
28,568,351
<blockquote> <h1>Is it possible to add a documentation string to a namedtuple in an easy manner?</h1> </blockquote> <h1>Python 3</h1> <p>In Python 3, you can easily alter the doc on your namedtuple:</p> <pre><code>NT = collections.namedtuple('NT', 'foo bar') NT.__doc__ = """:param str foo: foo name :param list bar: List of bars to bar""" </code></pre> <p>Which allows us to view the intent for them when we call help on them:</p> <pre><code>Help on class NT in module __main__: class NT(builtins.tuple) | :param str foo: foo name | :param list bar: List of bars to bar ... </code></pre> <p>This is really straightforward compared to the difficulties we have accomplishing the same thing in Python 2.</p> <h1>Python 2</h1> <p>In Python 2, you'll need to</p> <ul> <li>subclass the namedtuple, and </li> <li>declare <code>__slots__ == ()</code> </li> </ul> <p>Declaring <code>__slots__</code> is <strong>an important part that the other answers here miss</strong> . </p> <p>If you don't, each instance will create a separate <code>__dict__</code> (the lack of <code>__slots__</code> won't otherwise impede the functionality, but the lightweightness of the tuple is a primary consideration in using namedtuples). You'll also want a <code>__repr__</code>, if you want what is echoed on the command line to give you an equivalent object:</p> <pre><code>NTBase = collections.namedtuple('NTBase', 'foo bar') class NT(NTBase): """ Individual foo bar, a namedtuple :param str foo: foo name :param list bar: List of bars to bar """ __slots__ = () </code></pre> <p>a <code>__repr__</code> like this is needed if you create the base namedtuple with a different name (like we did above with the name string argument, <code>'NTBase'</code>):</p> <pre><code> def __repr__(self): return 'NT(foo={0}, bar={1})'.format( repr(self.foo), repr(self.bar)) </code></pre> <p>To test the repr, instantiate, then test for equality of a pass to <code>eval(repr(instance))</code></p> <pre><code>nt = NT('foo', 'bar') assert eval(repr(nt)) == nt </code></pre> <h2>Example from the documentation</h2> <p>The <a href="https://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields" rel="nofollow">docs also</a> give such an example, regarding <code>__slots__</code> - I'm adding my own docstring to it:</p> <blockquote> <pre><code>class Point(namedtuple('Point', 'x y')): """Docstring added here, not in original""" __slots__ = () @property def hypot(self): return (self.x ** 2 + self.y ** 2) ** 0.5 def __str__(self): return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot) </code></pre> <p>...</p> <p>The subclass shown above sets <code>__slots__</code> to an empty tuple. This helps keep memory requirements low by preventing the creation of instance dictionaries.</p> </blockquote> <p>This demonstrates in-place usage (like another answer here suggests), but note that the in-place usage may become confusing when you look at the method resolution order, if you're debugging, which is why I originally suggested using <code>Base</code> as a suffix for the base namedtuple:</p> <pre><code>&gt;&gt;&gt; Point.mro() [&lt;class '__main__.Point'&gt;, &lt;class '__main__.Point'&gt;, &lt;type 'tuple'&gt;, &lt;type 'object'&gt;] # ^^^^^---------------------^^^^^-- same names! </code></pre> <p>To prevent creation of a <code>__dict__</code> when subclassing from a class that uses it, you must also declare it in the subclass. See also <a href="http://stackoverflow.com/a/28059785/541136">this answer for more caveats on using <code>__slots__</code></a>.</p>
10
2015-02-17T18:19:22Z
[ "python", "docstring", "namedtuple" ]
Adding docstrings to namedtuples?
1,606,436
<p>Is it possible to add a documentation string to a namedtuple in an easy manner?</p> <p>I tried</p> <pre><code>from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) print Point.__doc__ # -&gt; "Point(x, y)" print Point2.__doc__ # -&gt; "Point2(x, y)" </code></pre> <p>but that doesn't cut it. Is it possible to do in some other way?</p>
39
2009-10-22T10:55:53Z
39,320,627
<p>Since Python 3.5, docstrings for <code>namedtuple</code> objects can be updated.</p> <p>From the <a href="https://docs.python.org/3/whatsnew/3.5.html#collections" rel="nofollow">whatsnew</a>:</p> <blockquote> <p><code>Point = namedtuple('Point', ['x', 'y']) Point.__doc__ += ': Cartesian coodinate' Point.x.__doc__ = 'abscissa' Point.y.__doc__ = 'ordinate'</code></p> </blockquote>
0
2016-09-04T19:20:42Z
[ "python", "docstring", "namedtuple" ]
How to use PIL to resize and apply rotation EXIF information to the file?
1,606,587
<p>I am trying to use Python to resize picture. With my camera, files are all written is landscape way.</p> <p>The exif information handle a tag to ask the image viewer to rotate in a way or another. Since most of the browser doesn't understand this information, I want to rotate the image using this EXIF information and keeping every other EXIF information.</p> <p>Do you know how I can do that using Python ?</p> <p>Reading the EXIF.py source code, I found something like that :</p> <pre><code>0x0112: ('Orientation', {1: 'Horizontal (normal)', 2: 'Mirrored horizontal', 3: 'Rotated 180', 4: 'Mirrored vertical', 5: 'Mirrored horizontal then rotated 90 CCW', 6: 'Rotated 90 CW', 7: 'Mirrored horizontal then rotated 90 CW', 8: 'Rotated 90 CCW'}) </code></pre> <p>How can I use this information and PIL to apply it ?</p>
20
2009-10-22T11:28:40Z
1,606,981
<p>First you have to make sure that your camera actually has a rotation sensor. Most camera models without sensor simply set the Orientation Tag to 1 (Horizontal) for ALL pictures.</p> <p>Then I recommend to use pyexiv2 and pyjpegtran in your case. PIL doesn't support lossless rotation, which is the domain of pyjpegtran. pyexiv2 is a library that allows you to copy metadata from one image to another (i think the method name is copyMetadata).</p> <p>Are you sure that you don't want to resize your photos before displaying them in the browser? A 8 Megapixel JPEG is much too big for the browser window and will cause endless loading times.</p>
2
2009-10-22T12:51:04Z
[ "python", "jpeg", "python-imaging-library", "rotation", "exif" ]
How to use PIL to resize and apply rotation EXIF information to the file?
1,606,587
<p>I am trying to use Python to resize picture. With my camera, files are all written is landscape way.</p> <p>The exif information handle a tag to ask the image viewer to rotate in a way or another. Since most of the browser doesn't understand this information, I want to rotate the image using this EXIF information and keeping every other EXIF information.</p> <p>Do you know how I can do that using Python ?</p> <p>Reading the EXIF.py source code, I found something like that :</p> <pre><code>0x0112: ('Orientation', {1: 'Horizontal (normal)', 2: 'Mirrored horizontal', 3: 'Rotated 180', 4: 'Mirrored vertical', 5: 'Mirrored horizontal then rotated 90 CCW', 6: 'Rotated 90 CW', 7: 'Mirrored horizontal then rotated 90 CW', 8: 'Rotated 90 CCW'}) </code></pre> <p>How can I use this information and PIL to apply it ?</p>
20
2009-10-22T11:28:40Z
1,608,545
<p>Although PIL can read EXIF metadata, it doesn't have the ability to change it and write it back to an image file.</p> <p>A better choice is the <a href="http://tilloy.net/dev/pyexiv2/index.htm">pyexiv2</a> library. With this library it's quite simple flip the photo's orientation. Here's an example:</p> <pre><code>import sys import pyexiv2 image = pyexiv2.Image(sys.argv[1]) image.readMetadata() image['Exif.Image.Orientation'] = 6 image.writeMetadata() </code></pre> <p>This sets the orientation to 6, corresponding to "Rotated 90 CW".</p>
6
2009-10-22T16:52:27Z
[ "python", "jpeg", "python-imaging-library", "rotation", "exif" ]
How to use PIL to resize and apply rotation EXIF information to the file?
1,606,587
<p>I am trying to use Python to resize picture. With my camera, files are all written is landscape way.</p> <p>The exif information handle a tag to ask the image viewer to rotate in a way or another. Since most of the browser doesn't understand this information, I want to rotate the image using this EXIF information and keeping every other EXIF information.</p> <p>Do you know how I can do that using Python ?</p> <p>Reading the EXIF.py source code, I found something like that :</p> <pre><code>0x0112: ('Orientation', {1: 'Horizontal (normal)', 2: 'Mirrored horizontal', 3: 'Rotated 180', 4: 'Mirrored vertical', 5: 'Mirrored horizontal then rotated 90 CCW', 6: 'Rotated 90 CW', 7: 'Mirrored horizontal then rotated 90 CW', 8: 'Rotated 90 CCW'}) </code></pre> <p>How can I use this information and PIL to apply it ?</p>
20
2009-10-22T11:28:40Z
1,608,846
<p>I finally used <a href="http://tilloy.net/dev/pyexiv2/">pyexiv2</a>, but it is a bit tricky to install on other platforms than GNU.</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2008-2009 Rémy HUBSCHER &lt;natim@users.sf.net&gt; - http://www.trunat.fr/portfolio/python.html # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # Using : # - Python Imaging Library PIL http://www.pythonware.com/products/pil/index.htm # - pyexiv2 http://tilloy.net/dev/pyexiv2/ ### # What is doing this script ? # # 1. Take a directory of picture from a Reflex Camera (Nikon D90 for example) # 2. Use the EXIF Orientation information to turn the image # 3. Remove the thumbnail from the EXIF Information # 4. Create 2 image one maxi map in 600x600, one mini map in 200x200 # 5. Add a comment with the name of the Author and his Website # 6. Copy the EXIF information to the maxi and mini image # 7. Name the image files with a meanful name (Date of picture) import os, sys try: import Image except: print "To use this program, you need to install Python Imaging Library - http://www.pythonware.com/products/pil/" sys.exit(1) try: import pyexiv2 except: print "To use this program, you need to install pyexiv2 - http://tilloy.net/dev/pyexiv2/" sys.exit(1) ############# Configuration ############## size_mini = 200, 200 size_maxi = 1024, 1024 # Information about the Photograph should be in ASCII COPYRIGHT="Remy Hubscher - http://www.trunat.fr/" ARTIST="Remy Hubscher" ########################################## def listJPEG(directory): "Retourn a list of the JPEG files in the directory" fileList = [os.path.normcase(f) for f in os.listdir(directory)] fileList = [f for f in fileList if os.path.splitext(f)[1] in ('.jpg', '.JPG')] fileList.sort() return fileList def _mkdir(newdir): """ works the way a good mkdir should :) - already exists, silently complete - regular file in the way, raise an exception - parent directory(ies) does not exist, make them as well """ if os.path.isdir(newdir): pass elif os.path.isfile(newdir): raise OSError("a file with the same name as the desired " \ "dir, '%s', already exists." % newdir) else: head, tail = os.path.split(newdir) if head and not os.path.isdir(head): _mkdir(head) if tail: os.mkdir(newdir) if len(sys.argv) &lt; 3: print "USAGE : python %s indir outdir [comment]" % sys.argv[0] exit indir = sys.argv[1] outdir = sys.argv[2] if len(sys.argv) == 4: comment = sys.argv[1] else: comment = COPYRIGHT agrandie = os.path.join(outdir, 'agrandie') miniature = os.path.join(outdir, 'miniature') print agrandie, miniature _mkdir(agrandie) _mkdir(miniature) for infile in listJPEG(indir): mini = os.path.join(miniature, infile) grand = os.path.join(agrandie, infile) file_path = os.path.join(indir, infile) image = pyexiv2.Image(file_path) image.readMetadata() # We clean the file and add some information image.deleteThumbnail() image['Exif.Image.Artist'] = ARTIST image['Exif.Image.Copyright'] = COPYRIGHT image.setComment(comment) # I prefer not to modify the input file # image.writeMetadata() # We look for a meanful name if 'Exif.Image.DateTime' in image.exifKeys(): filename = image['Exif.Image.DateTime'].strftime('%Y-%m-%d_%H-%M-%S.jpg') mini = os.path.join(miniature, filename) grand = os.path.join(agrandie, filename) else: # If no exif information, leave the old name mini = os.path.join(miniature, infile) grand = os.path.join(agrandie, infile) # We create the thumbnail #try: im = Image.open(file_path) im.thumbnail(size_maxi, Image.ANTIALIAS) # We rotate regarding to the EXIF orientation information if 'Exif.Image.Orientation' in image.exifKeys(): orientation = image['Exif.Image.Orientation'] if orientation == 1: # Nothing mirror = im.copy() elif orientation == 2: # Vertical Mirror mirror = im.transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 3: # Rotation 180° mirror = im.transpose(Image.ROTATE_180) elif orientation == 4: # Horizontal Mirror mirror = im.transpose(Image.FLIP_TOP_BOTTOM) elif orientation == 5: # Horizontal Mirror + Rotation 90° CCW mirror = im.transpose(Image.FLIP_TOP_BOTTOM).transpose(Image.ROTATE_90) elif orientation == 6: # Rotation 270° mirror = im.transpose(Image.ROTATE_270) elif orientation == 7: # Horizontal Mirror + Rotation 270° mirror = im.transpose(Image.FLIP_TOP_BOTTOM).transpose(Image.ROTATE_270) elif orientation == 8: # Rotation 90° mirror = im.transpose(Image.ROTATE_90) # No more Orientation information image['Exif.Image.Orientation'] = 1 else: # No EXIF information, the user has to do it mirror = im.copy() mirror.save(grand, "JPEG", quality=85) img_grand = pyexiv2.Image(grand) img_grand.readMetadata() image.copyMetadataTo(img_grand) img_grand.writeMetadata() print grand mirror.thumbnail(size_mini, Image.ANTIALIAS) mirror.save(mini, "JPEG", quality=85) img_mini = pyexiv2.Image(mini) img_mini.readMetadata() image.copyMetadataTo(img_mini) img_mini.writeMetadata() print mini print </code></pre> <p>If you see something that could be improved (except the fact that it is still for Python 2.5) then please let me know.</p>
14
2009-10-22T17:47:02Z
[ "python", "jpeg", "python-imaging-library", "rotation", "exif" ]
Timer in Python
1,606,700
<p>I am writing a python app using Tkinter for buttons and graphics and having trouble getting a timer working, what I need is a sample app that has three buttons and a label.</p> <p>[start timer] [stop timer] [quit]</p> <p>When I press the start button a function allows the label to count up from zero every 5 seconds, the stop button stops the timer and the quit button quits the app.</p> <p>I need to be able to press stop timer and quit at any time, and the time.sleep(5) function locks everything up so I can't use that.</p> <p>currently i'm using threading.timer(5,do_count_function) and getting nowhere !</p> <p>I'm a vb.net programmer, so python is a bit new to me, but hey, i'm trying.</p>
1
2009-10-22T11:53:54Z
1,606,815
<p>Check the .after method of your Tk() object. This allows you to use Tk's timer to fire events within the gui's own loop by giving it a length of time and a callback method.</p>
2
2009-10-22T12:19:21Z
[ "python", "tkinter" ]
Python debugging in Netbeans
1,606,746
<p>I have a problem with debugging Python programs under the Netbeans IDE. When I start debugging, the debugger writes the following log and error. Thank you for help.</p> <pre> [LOG]PythonDebugger : overall Starting >>>[LOG]PythonDebugger.taskStarted : I am Starting a new Debugging Session ... [LOG]This window is an interactive debugging context aware Python Shell [LOG]where you can enter python console commands while debugging >>>c:\documents and settings\aster\.netbeans\6.7\config\nbpython\debug\nbpythondebug\jpydaemon.py args = ['C:\\Documents and Settings\\aster\\.netbeans\\6.7\\config\\nbPython\\debug\\nbpythondebug\\jpydaemon.py', 'localhost', '11111'] localDebuggee= None JPyDbg connecting localhost on in= 11111 /out= 11112 ERROR:JPyDbg connection failed errno(10061) : Connection refused Debug session normal end ERROR :: Server Socket listen for debuggee has timed out (more than 20 seconds wait) java.net.SocketTimeoutException: Accept timed out </pre> <p>thanks for answer</p>
4
2009-10-22T12:02:30Z
1,606,803
<p>I just installed Python for NetBeans yesterday and hadn't tried the debugger, so just tried it, and I got the same error. So I thought maybe it's a Firewall issue, disabled my Firewall and retried it, and then it worked.</p> <p>However I restarted the Firewall and now it's still working, so I don't know. I saw the Netbeans options for Python have an input to specify the beginning listening port (which mine was 29000 not 11111 like yours).</p>
1
2009-10-22T12:16:04Z
[ "python", "netbeans" ]
Python debugging in Netbeans
1,606,746
<p>I have a problem with debugging Python programs under the Netbeans IDE. When I start debugging, the debugger writes the following log and error. Thank you for help.</p> <pre> [LOG]PythonDebugger : overall Starting >>>[LOG]PythonDebugger.taskStarted : I am Starting a new Debugging Session ... [LOG]This window is an interactive debugging context aware Python Shell [LOG]where you can enter python console commands while debugging >>>c:\documents and settings\aster\.netbeans\6.7\config\nbpython\debug\nbpythondebug\jpydaemon.py args = ['C:\\Documents and Settings\\aster\\.netbeans\\6.7\\config\\nbPython\\debug\\nbpythondebug\\jpydaemon.py', 'localhost', '11111'] localDebuggee= None JPyDbg connecting localhost on in= 11111 /out= 11112 ERROR:JPyDbg connection failed errno(10061) : Connection refused Debug session normal end ERROR :: Server Socket listen for debuggee has timed out (more than 20 seconds wait) java.net.SocketTimeoutException: Accept timed out </pre> <p>thanks for answer</p>
4
2009-10-22T12:02:30Z
1,636,617
<p>For Python I like WingIDE from Wingware.</p>
1
2009-10-28T11:14:12Z
[ "python", "netbeans" ]
catching stdout in realtime from subprocess
1,606,795
<p>I have read tons of posts but still can't seem to figure it out.</p> <p>I want to subprocess.Popen() rsync.exe in windows, and print the stdout in python.</p> <p>My code works, but it doesn't catch the progress until a file is done transfered! I want to print the progress for each file in realtime.</p> <p>Using python 3.1 now since I heard it should be better at handling IO.</p> <pre><code>import subprocess, time, os, sys cmd = "rsync.exe -vaz -P source/ dest/" p, line = True, 'start' p = subprocess.Popen(cmd, shell=True, bufsize=64, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE) for line in p.stdout: print("&gt;&gt;&gt; " + str(line.rstrip())) p.stdout.flush() </code></pre>
39
2009-10-22T12:14:43Z
1,606,859
<p>Change the stdout from the rsync process to be unbuffered.</p> <pre><code>p = subprocess.Popen(cmd, shell=True, bufsize=0, # 0=unbuffered, 1=line-buffered, else buffer-size stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE) </code></pre>
2
2009-10-22T12:26:39Z
[ "python", "subprocess", "stdout" ]