将函数转换为lambda

时间:2014-09-20 00:57:22

标签: python function class lambda getch

此代码检查系统是Windows还是Linux,导入所需的库,并定义正常工作的“getch”功能。
但是......函数“_d”可以在lambda中完成吗?

def _d():
    import sys, tty, termios
    f = sys.stdin.fileno()
    o = termios.tcgetattr(f)
    try:
        tty.setraw(sys.stdin.fileno())
        c = sys.stdin.read(1)
    finally:
        termios.tcsetattr(f, termios.TCSADRAIN, o)
    return c

_u = type('', (), {
    '__init__': lambda s: setattr(s, '', (None for sys in [__import__('sys')] for tty in [__import__('tty')])),
    '__call__': _d()
})

_w = None if ImportError else __import__("msvcrt").getch()

getch = (type('', (), {
    '__init__': lambda s: setattr(s, 'i', _u()) if ImportError else setattr(s, 'i', _w()),
    '__call__': lambda s: s.i()
}))()


我目前有:

setattr(type('',(),{}), '', (
    None for sys in [__import__('sys')]
    for tty in [__import__('tty')]
    for termios in [__import__('termios')]
    for f in sys.stdin.fileno()
    for o in termios.tcgetattr(f)
    for _ in tty.setraw(sys.stdin.fileno())
    for c in sys.stdin.read(1)
    for _ in termios.tcsetattr(f, termios.TCSADRAIN, o)
))

但那不让我回“c”。

1 个答案:

答案 0 :(得分:0)

好吧,如果你必须:

lambda: exec("""
def _d():
    import sys, tty, termios
    f = sys.stdin.fileno()
    o = termios.tcgetattr(f)
    try:
        tty.setraw(sys.stdin.fileno())
        c = sys.stdin.read(1)
    finally:
        termios.tcsetattr(f, termios.TCSADRAIN, o)
    return c
""", globals()) or _d()

它似乎比其他选择更具可读性。


要修复您给定的代码,请尝试:

lambda: next(
    c
    for sys in [__import__('sys')]
    for tty in [__import__('tty')]
    for termios in [__import__('termios')]
    for f in [sys.stdin.fileno()]
    for o in [termios.tcgetattr(f)]
    for _ in [tty.setraw(sys.stdin.fileno())]
    for c in [sys.stdin.read(1)]
    for _ in [termios.tcsetattr(f, termios.TCSADRAIN, o)]
)