Search code examples
androidpythongetchartermux

getchar in python returns permission denied (andorid 8.0)


I am working on termux, android 8.0.

I am using the following implementation of getchar:

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

The call to tcsetattr returns permission denied. A new security feature I guess.

Traceback (most recent call last):
  File "piano.py", line 103, in <module>
    char=getch()
  File "piano.py", line 21, in __call__
    def __call__(self): return self.impl()
  File "piano.py", line 33, in __call__
    tty.setraw(sys.stdin.fileno())
  File "/data/data/com.termux/files/usr/lib/python3.6/tty.py", line 28, in setraw
    tcsetattr(fd, when, mode)
termios.error: (13, 'Permission denied')

How to overcome this? (readchar package raises the same error)

Thanks.


Solution

  • Well, this is my solution.

    class _GetchUnix:
        def __init__(self):
            import tty, sys
    
        def __call__(self):
            import subprocess,sys
            t=subprocess.check_output(['bash','-c','read -s -n1 ans; echo $ans'],stdin=sys.stdin)
            return chr(t[0])