python - 如何将协调的元素写入给定的控制台?

标签 python linux console terminal coords

给定下一个控制台:

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 = []

现在我必须在该缓冲区中获取一些字母,但是字母的顺序不正确,有些地方将是空的。例如:我想在第 12 列和第 14 行的屏幕上有一个“w”,然后在其他地方有一些其他的“w”,在那里有一个“b”等等......(控制台很大足以处理这个)。我怎么能实现这个?我真的不知道如何解决这个问题。

另一个困扰我的问题是如何调用这个exit-constructor,应该给什么样的参数?

真诚的,一个真正没有经验的程序员。

最佳答案

回答你问题的第二部分......

您应该使用 with 语句调用 class Console。这将自动调用 __enter____exit__ 例程。例如:

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

运行它:

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

输出:

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

__exit__ 的参数与异常有关。如果退出 with 语句时没有异常,则所有参数(exception_type、exception_instance、exception_traceback)都将为 None。这是一个示例,显示了如何使用 exit 参数......

有异常(exception)的例子:

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

输出:

 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!')

在这里查看“With-Statement”和“上下文管理器”..

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

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

关于python - 如何将协调的元素写入给定的控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13514131/

相关文章:

python - 如果一个失败了,如何跳过类里面的其余测试?

c - 不存在的 sstk() 系统调用的用法示例?

.net - 如何在 Linux 中从 .NET Core 2.0 创建可执行控制台应用程序?

iphone - Mac 的 "console pane"应用程序的 "Instruments"中哪些命令有效? (例如,在仪器中)

java - 在 Java 中设置默认的 System.exit 代码?

vb.net - 如何通过键入 EXIT 来关闭控制台应用程序?

python - 将列表列表分为两部分的好方法,以内部列表中的值为条件

python - 导入错误 : cannot import name 'PackageFinder'

python - 如何区分 django 模板中的列表和字符串

c - Linux/C : Writing command-line arguments to a text file as separate lines?