Python 将函数转换为lambda
这段代码检查系统是Windows还是Linux,导入所需的libs,并定义一个正常工作的getch函数。 但是这个功能可以在lambda中完成吗Python 将函数转换为lambda,python,function,class,lambda,getch,Python,Function,Class,Lambda,Getch,这段代码检查系统是Windows还是Linux,导入所需的libs,并定义一个正常工作的getch函数。 但是这个功能可以在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)
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.如果您必须:
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)]
)
哇!你到底为什么要那样做?还有,lambda s:_d应该是_d,因为。thx,在我更改了u中的代码后,我错过了这个。这是一个非常非常糟糕的主意。钉子插不进洞里,好吗?请不要把它塞进肚子里。你要打破这个该死的东西。不需要把答案编辑成问题。最好让问题就是问题,答案就是答案。顺便说一句,使用if语句不能捕捉异常。@WilliamFernandes好吧,那么最好使用Perl。在Python可读性计数中。@AshwiniChaudhary我试图将整个代码放入一个变量语句中,以便在Python脚本中使用它。