sys.stdin.fileno

Here are the examples of the python api sys.stdin.fileno taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

131 Examples 7

Example 1

Project: django-windows-tools Source File: winfcgi.py
    def run(self):
        msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
        stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0)
        stdout = os.fdopen(sys.stdin.fileno(), 'wb', 0)

        conn = Connection(stdin, stdout, self)
        try:
            conn.run()
        except Exception as e:
            logging.exception(e)
            raise

Example 2

Project: tile-generator Source File: opsmgr.py
def ssh_interactive(tty):
	while True:
		rlist, wlist, xlist = select.select([sys.stdin.fileno(), tty], [], [])
		if sys.stdin.fileno() in rlist:
			input = os.read(sys.stdin.fileno(), 1024)
			if len(input) == 0:
				break
			else:
				os.write(tty, input)
				os.fsync(tty)
		elif tty in rlist:
			output = os.read(tty, 1024)
			if len(output) == 0:
				break
			sys.stdout.write(output)
			sys.stdout.flush()
	os.close(tty)

Example 3

Project: cylc Source File: plugins.py
    def _is_daemonized(self):
        """Return boolean indicating if the current process is
        running as a daemon.

        The criteria to determine the `daemon` condition is to verify
        if the current pid is not the same as the one that got used on
        the initial construction of the plugin *and* the stdin is not
        connected to a terminal.

        The sole validation of the tty is not enough when the plugin
        is executing inside other process like in a CI tool
        (Buildbot, Jenkins).
        """
        if (self._original_pid != os.getpid() and
            not os.isatty(sys.stdin.fileno())):
            return True
        else:
            return False

Example 4

Project: Cyprium Source File: ui.py
    @classmethod
    def _getch_unix(cl, echo=False):
        import tty
        import 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)
        if echo:
            cl.cprint(ch, end="")
        return ch

Example 5

Project: sc2reader Source File: sc2replayer.py
    def getch():
        fd = sys.stdin.fileno()
        oldterm = termios.tcgetattr(fd)
        newattr = termios.tcgetattr(fd)
        newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
        termios.tcsetattr(fd, termios.TCSANOW, newattr)
        oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
        try:
            while 1:
                try:
                    sys.stdin.read(1)
                    break
                except IOError:
                    pass
        finally:
            termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
            fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

Example 6

Project: nzbToMedia Source File: input.py
	def getch():
		fd = sys.stdin.fileno()
		old = termios.tcgetattr(fd)
		try:
			tty.setraw(fd)
			return sys.stdin.read(1)
		finally:
			termios.tcsetattr(fd, termios.TCSADRAIN, old)

Example 7

Project: TACTIC Source File: logtest.py
    def getchar():
        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)
        return ch

Example 8

Project: spreads Source File: cli.py
Function: getch
    def getch():
        """ Waits for a single character to be entered on stdin and returns it.

        :return:    Character that was entered
        :rtype:     str
        """
        fd = sys.stdin.fileno()
        old = termios.tcgetattr(fd)
        char = None
        try:
            tty.setraw(fd)
            char = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old)
        return char

Example 9

Project: reviewboard Source File: rbssh.py
Function: process_stdin
    def process_stdin(self, channel):
        """Read data from stdin and send it over the channel."""
        logging.debug('!! process_stdin\n')

        try:
            buf = os.read(sys.stdin.fileno(), 1)
        except OSError:
            buf = None

        if not buf:
            logging.debug('!! stdin empty\n')
            return False

        channel.send(buf)

        return True

Example 10

Project: funcparserlib Source File: json.py
Function: main
def main():
    logging.basicConfig(level=logging.DEBUG)
    try:
        stdin = os.fdopen(sys.stdin.fileno(), 'rb')
        input = stdin.read().decode(ENCODING)
        tree = loads(input)
        print pformat(tree)
    except (NoParseError, LexerError), e:
        msg = (u'syntax error: %s' % e).encode(ENCODING)
        print >> sys.stderr, msg
        sys.exit(1)

Example 11

Project: PySixel Source File: cellsize.py
Function: set_raw
    def __set_raw(self):
        fd = sys.stdin.fileno()
        backup = termios.tcgetattr(fd)
        try:
            new = termios.tcgetattr(fd)
            new[0] = 0  # c_iflag = 0
            new[3] = 0  # c_lflag = 0
            new[3] = new[3] & ~(termios.ECHO | termios.ICANON)
            termios.tcsetattr(fd, termios.TCSANOW, new)
        except Exception:
            termios.tcsetattr(fd, termios.TCSANOW, backup)
        return backup

Example 12

Project: playerpiano Source File: piano.py
@contextlib.contextmanager
def frob_tty():
    """massage the terminal to not echo characters & the like"""
    stdin_fd = sys.stdin.fileno()
    old_mask = termios.tcgetattr(stdin_fd)
    new = old_mask[:]
    LFLAGS = 3
    new[LFLAGS] &= ~termios.ECHO
    termios.tcsetattr(stdin_fd, termios.TCSADRAIN, new)
    tty.setraw(stdin_fd)
    try:
        yield
    finally:
        # restore the terminal to its original state
        termios.tcsetattr(stdin_fd, termios.TCSADRAIN, old_mask)

Example 13

Project: cgstudiomap Source File: shell.py
    def console(self, local_vars):
        if not os.isatty(sys.stdin.fileno()):
            exec sys.stdin in local_vars
        else:
            if 'env' not in local_vars:
                print('No environment set, use `odoo.py shell -d dbname`'
                      ' to get one.')
            for i in sorted(local_vars):
                print('%s: %s' % (i, local_vars[i]))
            logging.disable(logging.CRITICAL)
            Console(locals=local_vars).interact()

Example 14

Project: SoCo Source File: analyse_ws.py
def getch():
    """ Read a single character non-echoed and return it. Recipe from:
    http://code.activestate.com/recipes/
    134892-getch-like-unbuffered-character-reading-from-stdin/
    """
    filedescriptor = sys.stdin.fileno()
    old_settings = termios.tcgetattr(filedescriptor)
    if PLATFORM == 'win32':
        character = msvcrt.getch()
    else:
        try:
            tty.setraw(sys.stdin.fileno())
            character = sys.stdin.read(1)
        finally:
            termios.tcsetattr(filedescriptor, termios.TCSADRAIN, old_settings)
    return character

Example 15

Project: Ramen Source File: ftpsync.py
def getpass(prompt = "Password: "):
    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    new = termios.tcgetattr(fd)
    new[3] = new[3] & ~termios.ECHO          # lflags
    try:
        termios.tcsetattr(fd, termios.TCSADRAIN, new)
        passwd = raw_input(prompt)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)
    return passwd

Example 16

Project: push Source File: cli.py
def read_character():
    "Read a single character from the terminal without echoing it."
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setcbreak(fd)
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch

Example 17

Project: targetcli Source File: cli.py
    def getchar(self):
        '''
        Returns the first character read from stdin, without waiting for the
        user to hit enter.
        '''
        fd = sys.stdin.fileno()
        tcattr_backup = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            char = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, tcattr_backup)
            return char

Example 18

Project: getline Source File: __linux_impl.py
Function: init
    def __init__(self, histfile=None):
        self.histfile = histfile
        self.fd = sys.stdin.fileno()
        self.curpos = [0, 0, 0]
        self.history = self.__loadhist()
        self.__init()

Example 19

Project: freeipa Source File: installutils.py
Function: get_password
def get_password(prompt):
    if os.isatty(sys.stdin.fileno()):
        return getpass.getpass(prompt)
    else:
        sys.stdout.write(prompt)
        sys.stdout.flush()
        line = sys.stdin.readline()
        if not line:
            raise EOFError()
        return line.rstrip()

Example 20

Project: pwndbg Source File: ui.py
def banner(title):
    title = title.upper()
    try:
        _height, width = struct.unpack('hh', fcntl.ioctl(sys.stdin.fileno(), termios.TIOCGWINSZ, '1234'))
    except:
        width = 80
    width -= 2
    return C.banner(("[{:%s^%ss}]" % (config.banner_separator, width)).format(title))

Example 21

Project: nepho Source File: common.py
def terminal_size():
    import fcntl
    import termios
    import struct
    h, w, hp, wp = struct.unpack('HHHH', fcntl.ioctl(
        sys.stdin.fileno(),
        termios.TIOCGWINSZ,
        struct.pack('HHHH', 0, 0, 0, 0)
    ))
    return w, h

Example 22

Project: playitagainsam Source File: util.py
Function: init
    def __init__(self, fd=None):
        if fd is None:
            fd = sys.stdin.fileno()
        elif hasattr(fd, "fileno"):
            fd = fd.fileno()
        self.fd = fd

Example 23

Project: aioconsole Source File: stream.py
@asyncio.coroutine
def create_standard_streams(stdin, stdout, loop):
    try:
        sys.stdin.fileno(), sys.stdout.fileno()
    except io.UnsupportedOperation:
        reader = NonFileStreamReader(stdin, loop=loop)
        writer = NonFileStreamWriter(stdout, loop=loop)
    else:
        future = open_pipe_connection(stdin, stdout, loop=loop)
        reader, writer = yield from future
    return reader, writer

Example 24

Project: pyload Source File: Getch.py
    def __call__(self):
        import sys
        import tty
        import 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)
        return ch

Example 25

Project: pgctl Source File: timestamp.py
Function: main
def main():
    import sys
    import io
    infile = io.open(sys.stdin.fileno(), buffering=0, mode='rb')
    outfile = io.open(sys.stdout.fileno(), buffering=0, mode='wb')
    prepend_timestamps(infile, outfile)

Example 26

Project: NOT_UPDATED_Sick-Beard-Dutch Source File: plugins.py
    def handle_SIGHUP(self):
        if os.isatty(sys.stdin.fileno()):
            # not daemonized (may be foreground or background)
            self.bus.log("SIGHUP caught but not daemonized. Exiting.")
            self.bus.exit()
        else:
            self.bus.log("SIGHUP caught while daemonized. Restarting.")
            self.bus.restart()

Example 27

Project: pysh Source File: evaluator.py
Function: to_file
  def tofile(self, fd):
    if fd == sys.stdin.fileno():
      return sys.stdin
    if fd == sys.stdout.fileno():
      return sys.stdout
    if fd in self.all_r:
      mode = 'r'
    elif fd in self.all_w:
      mode = 'w'
    else:
      raise Exception('Unknown file descriptor: ' + str(fd))
    if fd in self.files:
      return self.files[fd]
    f = os.fdopen(fd, mode)
    self.files[fd] = f
    return f

Example 28

Project: raspirobotboard3 Source File: 08_manual_robot_continuous.py
def readchar():
    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)
    if ch == '0x03':
        raise KeyboardInterrupt
    return ch

Example 29

Project: django-nonrel Source File: autoreload.py
def ensure_echo_on():
    if termios:
        fd = sys.stdin.fileno()
        attr_list = termios.tcgetattr(fd)
        if not attr_list[3] & termios.ECHO:
            attr_list[3] |= termios.ECHO
            termios.tcsetattr(fd, termios.TCSANOW, attr_list)

Example 30

Project: babel Source File: download_import_cldr.py
def get_terminal_width():
    try:
        import fcntl
        import termios
        import struct
        fd = sys.stdin.fileno()
        cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
        return cr[1]
    except Exception:
        return 80

Example 31

Project: deltaic Source File: __init__.py
Function: init
    def __init__(self, settings):
        self._spool_dir = settings['archive-spool']
        self._tar = settings.get('archive-tar-path', 'tar')
        self._gpg = settings.get('archive-gpg-path', 'gpg2')
        self._gpg_recipients = settings.get('archive-gpg-recipients')
        self._gpg_signing_key = settings.get('archive-gpg-signing-key')

        self._gpg_env = dict(os.environ)
        try:
            # Required for GPG passphrase prompting
            self._gpg_env['GPG_TTY'] = os.ttyname(sys.stdin.fileno())
        except OSError:
            # stdin is not a tty
            pass

        self.encryption = 'gpg' if self._gpg_recipients else 'none'

Example 32

Project: odoo-development Source File: getch.py
    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)
        return ch

Example 33

Project: vent Source File: menu_launcher.py
def getch():
    try:
        fd = sys.stdin.fileno()
        settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
        return ch
    except Exception as e: # pragma: no cover
        pass

Example 34

Project: skypipe Source File: client.py
def stream_stdin_lines():
    """Generator for unbuffered line reading from STDIN"""
    stdin = os.fdopen(sys.stdin.fileno(), 'r', 0)
    while True:
        line = stdin.readline()
        if line:
            yield line
        else:
            break

Example 35

Project: junk Source File: ui_tty.py
  @staticmethod
  def reset():
    old = (tty.tcgetattr(sys.stdin.fileno()), tty.tcgetattr(sys.stdout.fileno()), tty.tcgetattr(sys.stderr.fileno()))
    import subprocess
    subprocess.call('reset')
    return old

Example 36

Project: thundergate Source File: linux.py
Function: enter
    def __enter__(self):
        fd = os.open("/dev/net/tun", os.O_RDWR)
        ifr = struct.pack('16sH', "", IFF_TAP | IFF_NO_PI)
        self.tap_name = struct.unpack('16sH', fcntl.ioctl(fd, TUNSETIFF, ifr))[0]
        print "[+] tap device name: \"%s\"" % self.tap_name
	self.tfd = fd
	self.confd = sys.stdin.fileno()
	try:
	    self.read_fds = [self.dev.interface.eventfd, self.tfd, self.confd]
	    self.ready = []
            self._wait_for_something = self.__wait_with_eventfd
            self._get_serial = self.__get_serial_from_eventfd
	except:
            print "[-] no interrupt eventfd exposed by device interface, polling instead."
            self._wait_for_something = self.__wait_by_polling
            self._get_serial = self.__get_serial_from_counter
        return self

Example 37

Project: rshell Source File: getch.py
    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.buffer.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
            return ch

Example 38

Project: headphones Source File: plugins.py
    def handle_SIGHUP(self):
        """Restart if daemonized, else exit."""
        if os.isatty(sys.stdin.fileno()):
            # not daemonized (may be foreground or background)
            self.bus.log("SIGHUP caught but not daemonized. Exiting.")
            self.bus.exit()
        else:
            self.bus.log("SIGHUP caught while daemonized. Restarting.")
            self.bus.restart()

Example 39

Project: pwnypack Source File: main.py
def binary_value_or_stdin(value):
    """
    Return fsencoded value or read raw data from stdin if value is None.
    """
    if value is None:
        reader = io.open(sys.stdin.fileno(), mode='rb', closefd=False)
        return reader.read()
    elif six.PY3:
        return os.fsencode(value)
    else:
        return value

Example 40

Project: Ultros Source File: console.py
    def __call__(self):
        import sys
        import tty
        import 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)
        return ch

Example 41

Project: portage Source File: repos.py
	def _vcs_gpg_git(self):
		# NOTE: It's possible to use --gpg-sign=key_id to specify the key in
		# the commit arguments. If key_id is unspecified, then it must be
		# configured by `git config user.signingkey key_id`.
		self.vcs_settings.vcs_local_opts.append("--gpg-sign")
		if self.repoman_settings.get("PORTAGE_GPG_DIR"):
			# Pass GNUPGHOME to git for bug #462362.
			self.commit_env["GNUPGHOME"] = self.repoman_settings["PORTAGE_GPG_DIR"]

		# Pass GPG_TTY to git for bug #477728.
		try:
			self.commit_env["GPG_TTY"] = os.ttyname(sys.stdin.fileno())
		except OSError:
			pass

Example 42

Project: marker Source File: readchar.py
def read_char():
    ''' Read a character '''
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(fd, termios.TCSADRAIN)
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch

Example 43

Project: hitchtest Source File: utils.py
def ipython(message=None, frame=None):
    """Launch into customized IPython with greedy autocompletion and no prompt to exit.
       If stdin is not tty, just issue warning message."""
    import sys
    if os.isatty(sys.stdin.fileno()):
        config = Config({
            'InteractiveShell': {'confirm_exit': False, },
            'IPCompleter': {'greedy': True, }
        })
        InteractiveShellEmbed.instance(config=config)(message, local_ns=frame.f_locals, global_ns=frame.f_globals)
    else:
        warn("==========> IPython cannot be launched if stdin is not a tty.\n\n")

Example 44

Project: term2048 Source File: keypress.py
    def __getKey():
        """Return a key pressed by the user"""
        try:
            tty.setcbreak(sys.stdin.fileno())
            termios.tcflush(sys.stdin, termios.TCIOFLUSH)
            ch = sys.stdin.read(1)
            return ord(ch) if ch else None
        finally:
            termios.tcsetattr(__fd, termios.TCSADRAIN, __old)

Example 45

Project: bup Source File: ftp-cmd.py
def inputiter():
    if os.isatty(sys.stdin.fileno()):
        while 1:
            try:
                yield raw_input('bup> ')
            except EOFError:
                print ''  # Clear the line for the terminal's next prompt
                break
    else:
        for line in sys.stdin:
            yield line

Example 46

Project: qb Source File: buzzer.py
    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)
            sys.stdin.flush()
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

Example 47

Project: qfc Source File: readchar.py
def read_char_no_blocking():
    ''' Read a character in nonblocking mode, if no characters are present in the buffer, return an empty string '''
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    old_flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    try:
        tty.setraw(fd, termios.TCSADRAIN)
        fcntl.fcntl(fd, fcntl.F_SETFL, old_flags | os.O_NONBLOCK)
        return sys.stdin.read(1)
    except IOError as e:
        ErrorNumber = e[0]
        # IOError with ErrorNumber 11(35 in Mac)  is thrown when there is nothing to read(Resource temporarily unavailable)
        if (sys.platform.startswith("linux") and ErrorNumber != 11) or (sys.platform == "darwin" and ErrorNumber != 35):
            raise
        return ""
    finally:
        fcntl.fcntl(fd, fcntl.F_SETFL, old_flags)
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

Example 48

Project: pyserial Source File: miniterm.py
        def __init__(self):
            super(Console, self).__init__()
            self.fd = sys.stdin.fileno()
            # an additional pipe is used in getkey, so that the cancel method
            # can abort the waiting getkey method
            self.pipe_r, self.pipe_w = os.pipe()
            self.old = termios.tcgetattr(self.fd)
            atexit.register(self.cleanup)
            if sys.version_info < (3, 0):
                self.enc_stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin)
            else:
                self.enc_stdin = sys.stdin

Example 49

Project: sfepy Source File: getch.py
    def __call__(self):
        tty, sys, select = self.mods

        fd = sys.stdin.fileno()
        old = tty.tcgetattr(fd)
        tty.setcbreak(fd, tty.TCSANOW)
        try:
            return sys.stdin.read(1)
        finally:
            tty.tcsetattr(fd, tty.TCSAFLUSH, old)

Example 50

Project: 217gdb Source File: ui.py
def get_term_size():
    try:
        height, width = struct.unpack('hh', fcntl.ioctl(sys.stdin.fileno(), termios.TIOCGWINSZ, '1234'))
    except:
        height = 60
        width = 80
    return (height, width)
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3