質問

given the next console:

import os
import tty
import termios
from sys import stdin

class Console(object):

    def __enter__(self):
        self.old_settings = termios.tcgetattr(stdin)
        self.buffer = []
        return self

    def __exit__(self, type, value, traceback):
        termios.tcsetattr(stdin, termios.TCSADRAIN, self.old_settings)

    ...

    def dimensions(self):
        dim = os.popen('stty size', 'r').read().split()
        return int(dim[1]), int(dim[0])

    def write(self, inp):
        if isinstance(inp, basestring):
            inp = inp.splitlines(False)
        if len(inp) == 0:
            self.buffer.append("")
        else:
            self.buffer.extend(inp)

    def printBuffer(self):
        self.clear()
        print "\n".join(self.buffer)
        self.buffer = []

Now I have to get some letters in that buffer, but letters aren't given in the right order and some places are going to be empty. For instance: I want to have a "w" on the screen in the 12th column and the 14th row and then some other "w"'s on other places and a "b" over there etc...(the console is big enough to handle this). How could I implement this? I really don't have a clue how to solve this problem.

Another question that bothers me is how to call this exit-constructor, what kinda parameters should be given?

sincerely, a really inexperienced programmer.

役に立ちましたか?

解決

To answer the 2nd part of your question ...

You should invoke class Console using the with statement. This will automatically call __enter__ and __exit__ routines. For example:

class CM(object):
    def __init__(self, arg):
         print 'Initializing arg .. with', arg
    def __enter__(self):
         print 'Entering CM'
    def __exit__(self, type, value, traceback):
         print 'Exiting CM'
         if type is IndexError:
             print 'Oh! .. an Index Error! .. must handle this'
             print 'Lets see what the exception args are ...', value.args
             return True

Running it:

with CM(10) as x:
    print 'Within CM'

Output:

Initializing arg .. with 10
Entering CM
Within CM
Exiting CM

The arguments to __exit__ are related to exceptions. If there are no exceptions when you exit the with statement then all arguments (exception_type, exception_instance, exception_traceback) will be None. Here's an example showing how the exit arguments can be used ...

Example with an exception:

with CM(10) as x:
    print 'Within CM'
    raise IndexError(1, 2, 'dang!')

Output:

 Initializing arg .. with 10
 Entering CM
 Within CM
 Exiting CM
 Oh! .. an Index Error! .. must handle this
 Lets see what the exception args are ... (1, 2, 'dang!')

Check out "With-Statement" and "Context Managers" here ..

http://docs.python.org/2/reference/compound_stmts.html#with

http://docs.python.org/2/reference/datamodel.html#context-managers

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top