sys.stdout.fileno

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

136 Examples 7

Example 1

Project: quickfind
Source File: Searcher.py
View license
    @contextmanager
    def redirStdout(self):
        stdout = os.dup(sys.stdout.fileno())
        os.dup2(sys.stderr.fileno(), sys.stdout.fileno())
        yield
        os.dup2(stdout, sys.stdout.fileno())

Example 2

Project: pexpect
Source File: script.py
View license
def sigwinch_passthrough (sig, data):

    # Check for buggy platforms (see pexpect.setwinsize()).
    if 'TIOCGWINSZ' in dir(termios):
        TIOCGWINSZ = termios.TIOCGWINSZ
    else:
        TIOCGWINSZ = 1074295912 # assume
    s = struct.pack ("HHHH", 0, 0, 0, 0)
    a = struct.unpack ('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ , s))
    global global_pexpect_instance
    global_pexpect_instance.setwinsize(a[0],a[1])

Example 3

Project: mock
Source File: util.py
View license
def resize_pty(pty):
    try:
        winsize = struct.pack('HHHH', 0, 0, 0, 0)
        winsize = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, winsize)
        fcntl.ioctl(pty, termios.TIOCSWINSZ, winsize)
    except IOError:
        # Nice to have, but not necessary
        pass

Example 4

Project: tarindexer
Source File: tarindexer.py
View license
def lookup(dbtarfile,indexfile,path):
    with open(dbtarfile, 'rb') as tar:
        with  open(indexfile, 'r') as outfile:
            for line in outfile.readlines():
                m = line[:-1].rsplit(" ", 2)
                if path == m[0]:
                    tar.seek(int(m[1]))
                    buffer = tar.read(int(m[2]))
                    os.write (sys.stdout.fileno (), buffer)

Example 5

Project: ginkgo
Source File: logger.py
View license
    def capture_stdio(self):
        # TODO: something smarter than this?
        try:
            os.dup2(logging._handlerList[0]().stream.fileno(), sys.stdout.fileno())
            os.dup2(logging._handlerList[0]().stream.fileno(), sys.stderr.fileno())
        except:
            pass

Example 6

Project: raspberry_pwn
Source File: script.py
View license
def sigwinch_passthrough (sig, data):

    # Check for buggy platforms (see pexpect.setwinsize()).
    if 'TIOCGWINSZ' in dir(termios):
        TIOCGWINSZ = termios.TIOCGWINSZ
    else:
        TIOCGWINSZ = 1074295912 # assume
    s = struct.pack ("HHHH", 0, 0, 0, 0)
    a = struct.unpack ('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ , s))
    global global_pexpect_instance
    global_pexpect_instance.setwinsize(a[0],a[1])

Example 7

Project: pymux
Source File: client.py
View license
    def _send_size(self):
        " Report terminal size to server. "
        rows, cols = _get_size(sys.stdout.fileno())
        self._send_packet({
            'cmd': 'size',
            'data': [rows, cols]
        })

Example 8

Project: pymux
Source File: client.py
View license
    def _send_size(self):
        " Report terminal size to server. "
        rows, cols = _get_size(sys.stdout.fileno())
        self._send_packet({
            'cmd': 'size',
            'data': [rows, cols]
        })

Example 9

Project: jhbuild
Source File: trayicon.py
View license
    def _run_zenity(self):
        # run zenity with stdout and stderr directed to /dev/null
        def preexec():
            null = open('/dev/null', 'w')
            try:
                os.dup2(null.fileno(), sys.stdout.fileno())
                os.dup2(null.fileno(), sys.stderr.fileno())
            finally:
                null.close()
            os.setsid()
        try:
            self.proc = subprocess.Popen(['zenity', '--notification',
                                          '--listen'],
                                         close_fds=True,
                                         preexec_fn=preexec,
                                         stdin=subprocess.PIPE)
        except (OSError, IOError):
            self.proc = None

Example 10

Project: dash-hack
Source File: table_formatter.py
View license
def getStdoutFilename():
    try:
        if os.name == "nt":
            import msvcrt, ctypes
            handle = msvcrt.get_osfhandle(sys.stdout.fileno())
            size = ctypes.c_ulong(1024)
            nameBuffer = ctypes.create_string_buffer(size.value)
            ctypes.windll.kernel32.GetFinalPathNameByHandleA(handle, nameBuffer, size, 4)
            return nameBuffer.value
        else:
            return os.readlink('/proc/self/fd/1')
    except:
        return ""

Example 11

Project: euca2ools
Source File: downloadbundle.py
View license
    def print_result(self, result):
        _, manifest_filename = result
        if (manifest_filename and
                (isinstance(self.args['dest'], basestring) or
                 self.args['dest'].fileno() != sys.stdout.fileno())):
            print 'Wrote manifest', manifest_filename

Example 12

Project: molecule
Source File: login.py
View license
    def _sigwinch_passthrough(self, sig, data):  # pragma: no cover
        TIOCGWINSZ = 1074295912  # assume
        if 'TIOCGWINSZ' in dir(termios):
            TIOCGWINSZ = termios.TIOCGWINSZ
        s = struct.pack('HHHH', 0, 0, 0, 0)
        a = struct.unpack('HHHH',
                          fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s))
        self._pt.setwinsize(a[0], a[1])

Example 13

Project: repl
Source File: util.py
View license
def get_terminal_size(fileno=None):
    if fileno is None:
        fileno = sys.stdout.fileno()

    buf = struct.pack('HHHH', 0, 0, 0, 0)
    res = fcntl.ioctl(fileno, termios.TIOCGWINSZ, buf)
    h, w, _, _ = struct.unpack('HHHH', res)

    return (w, h)

Example 14

Project: trigger
Source File: cli.py
View license
    def __init__(self, start_msg="", done_msg="", max=100):
        self.unbuff = os.fdopen(sys.stdout.fileno(), 'w', 0)
        self.start_msg = start_msg
        self.done_msg = done_msg
        self.max = max
        self.whirlygig = ['|', '/', '-', '\\']
        self.whirl    = self.whirlygig[:]
        self.first = False

Example 15

Project: Tardis
Source File: List.py
View license
def computeColumnWidth(names):
    if len(names) == 0:
        return (1, '%s')
    longestName = max(map(len, names))

    if args.columns:
        columns = args.columns
    else:
        if os.isatty(sys.stdout.fileno()):
            height, width = Util.getTerminalSize()
            width -= 2          # lop a couple characters off the end to avoid annoying wraps in some cases.
            columns = width / (longestName + 4)
        else:
            columns = 1

    fmt = "%%-%ds  " % (longestName + 2)

    return (columns, fmt)

Example 16

Project: pysh
Source File: parser.py
View license
  def parseRedirectToken(self, tok):
    m = REDIRECT_PATTERN.match(tok[1])
    src_num = sys.stdout.fileno()
    if m.group(1):
      src_num = int(m.group(1))
    append = False
    if m.group(2):
      append = True
    dst_num = -1
    if m.group(3):
      dst_num = int(m.group(3))
    if append and dst_num != -1:
      raise Exception('Can not use both >> and &%d.' % dst_num)
    return append, src_num, dst_num

Example 17

Project: python-deployer
Source File: socket_client.py
View license
def get_size():
    # Buffer for the C call
    buf = array.array('h', [0, 0, 0, 0 ])

    # Do TIOCGWINSZ (Get)
    fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, buf, True)

    # Return rows, cols
    return buf[0], buf[1]

Example 18

Project: cylc
Source File: daemonize.py
View license
def redirect(logd):
    """Redirect standard file descriptors

    Note that simply reassigning the sys streams is not sufficient
    if we import modules that write to stdin and stdout from C
    code - evidently the subprocess module is in this category!
    """
    sout = file(os.path.join(logd, SuiteLog.OUT), 'a+', 0)  # 0 => unbuffered
    serr = file(os.path.join(logd, SuiteLog.ERR), 'a+', 0)
    dvnl = file(os.devnull, 'r')
    os.dup2(sout.fileno(), sys.stdout.fileno())
    os.dup2(serr.fileno(), sys.stderr.fileno())
    os.dup2(dvnl.fileno(), sys.stdin.fileno())

Example 19

Project: jumpserver
Source File: connect.py
View license
    @staticmethod
    def get_win_size():
        """
        This function use to get the size of the windows!
        获得terminal窗口大小
        """
        if 'TIOCGWINSZ' in dir(termios):
            TIOCGWINSZ = termios.TIOCGWINSZ
        else:
            TIOCGWINSZ = 1074295912L
        s = struct.pack('HHHH', 0, 0, 0, 0)
        x = fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s)
        return struct.unpack('HHHH', x)[0:2]

Example 20

Project: cppman
Source File: util.py
View license
def get_width():
    """Get terminal width"""
    # Get terminal size
    ws = struct.pack("HHHH", 0, 0, 0, 0)
    ws = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, ws)
    lines, columns, x, y = struct.unpack("HHHH", ws)
    width = int(columns * 39 / 40)
    if width >= columns - 2:
        width = columns - 2
    return width

Example 21

Project: llvm-p86
Source File: compiler.py
View license
    def save_obj_code(self, out, triple='', cpu='', attrs=''):

        if self.ctx is None or self.ctx.module is None:
            return

        if not cpu: cpu = 'generic'

        tm = ee.TargetMachine.new(triple, cpu, attrs, 0)
        obj = tm.emit_object(self.ctx.module)

        if out == '-':
            os.write(sys.stdout.fileno(), obj)
        else:
            f = self._open_file(out)
            f.write(obj)
            f.close()

Example 22

Project: freedoom
Source File: playpal.py
View license
def output_palette(pal):

	for color in palette:
		color = tuple(map(clamp_pixval, color))
		
		encoded = struct.pack("BBB", *color)
		os.write(sys.stdout.fileno(), encoded)

Example 23

Project: llvm-p86
Source File: compiler.py
View license
    def save_bit_code(self, out, triple=''):

        if self.ctx is None or self.ctx.module is None:
            return

        tm = ee.TargetMachine.new(triple)
        self.ctx.module.target = str(tm.triple)
        self.ctx.module.data_layout = str(tm.target_data)

        bc = self.ctx.module.to_bitcode()

        if out == '-':
            os.write(sys.stdout.fileno(), bc)
        else:
            f = self._open_file(out)
            f.write(bc)
            f.close()

Example 24

Project: ntfy
Source File: terminal.py
View license
def darwin_iterm2_shell_is_focused():
    focused_tty = osascript_tell(
        'iTerm',
        'tty of current session of current terminal',
    )
    return focused_tty == ttyname(stdout.fileno())

Example 25

Project: mididings
Source File: misc.py
View license
def get_terminal_size():
    """
    Return the height and width of the terminal.
    """
    try:
        s = struct.pack("HHHH", 0, 0, 0, 0)
        fd = sys.stdout.fileno()
        x = fcntl.ioctl(fd, termios.TIOCGWINSZ, s)
        t = struct.unpack("HHHH", x)
        return t[0], t[1]
    except Exception:
        return 25, 80

Example 26

Project: pyserial
Source File: miniterm.py
View license
        def __init__(self):
            super(Console, self).__init__()
            self._saved_ocp = ctypes.windll.kernel32.GetConsoleOutputCP()
            self._saved_icp = ctypes.windll.kernel32.GetConsoleCP()
            ctypes.windll.kernel32.SetConsoleOutputCP(65001)
            ctypes.windll.kernel32.SetConsoleCP(65001)
            self.output = codecs.getwriter('UTF-8')(Out(sys.stdout.fileno()), 'replace')
            # the change of the code page is not propagated to Python, manually fix it
            sys.stderr = codecs.getwriter('UTF-8')(Out(sys.stderr.fileno()), 'replace')
            sys.stdout = self.output
            self.output.encoding = 'UTF-8'  # needed for input

Example 27

Project: repl
Source File: util.py
View license
def get_terminal_size(fileno=None):
    if fileno is None:
        fileno = sys.stdout.fileno()

    buf = struct.pack('HHHH', 0, 0, 0, 0)
    res = fcntl.ioctl(fileno, termios.TIOCGWINSZ, buf)
    h, w, _, _ = struct.unpack('HHHH', res)

    return (w, h)

Example 28

Project: molecule
Source File: login.py
View license
    def _sigwinch_passthrough(self, sig, data):  # pragma: no cover
        TIOCGWINSZ = 1074295912  # assume
        if 'TIOCGWINSZ' in dir(termios):
            TIOCGWINSZ = termios.TIOCGWINSZ
        s = struct.pack('HHHH', 0, 0, 0, 0)
        a = struct.unpack('HHHH',
                          fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s))
        self._pt.setwinsize(a[0], a[1])

Example 29

Project: Tardis
Source File: List.py
View license
def computeColumnWidth(names):
    if len(names) == 0:
        return (1, '%s')
    longestName = max(map(len, names))

    if args.columns:
        columns = args.columns
    else:
        if os.isatty(sys.stdout.fileno()):
            height, width = Util.getTerminalSize()
            width -= 2          # lop a couple characters off the end to avoid annoying wraps in some cases.
            columns = width / (longestName + 4)
        else:
            columns = 1

    fmt = "%%-%ds  " % (longestName + 2)

    return (columns, fmt)

Example 30

Project: Ciao
Source File: ciaomcu.py
View license
	def write(self, status, message, data = None):
		output = [ str(status), str(message) ]
		if not data is None:
			data = utils.serialize(data)
			output.append(data.tostring())
		#4 (ASCII) means end trasmit (like newline but via a non-printable char)
		os.write(sys.stdout.fileno(), ";".join(output)+ chr(4))

Example 31

Project: pexpect
Source File: sigwinch_report.py
View license
def getwinsize():
    '''This returns the window size of the child tty.
    The return value is a tuple of (rows, cols).
    '''
    if 'TIOCGWINSZ' in dir(termios):
        TIOCGWINSZ = termios.TIOCGWINSZ
    else:
        TIOCGWINSZ = 1074295912 # Assume
    s = struct.pack('HHHH', 0, 0, 0, 0)
    x = fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s)
    return struct.unpack('HHHH', x)[0:2]

Example 32

Project: jumpserver
Source File: connect.py
View license
    @staticmethod
    def get_win_size():
        """
        This function use to get the size of the windows!
        获得terminal窗口大小
        """
        if 'TIOCGWINSZ' in dir(termios):
            TIOCGWINSZ = termios.TIOCGWINSZ
        else:
            TIOCGWINSZ = 1074295912L
        s = struct.pack('HHHH', 0, 0, 0, 0)
        x = fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s)
        return struct.unpack('HHHH', x)[0:2]

Example 33

Project: python-capturer
Source File: tests.py
View license
    def test_error_handling(self):
        # Nested CaptureOutput.start_capture() calls should raise an exception.
        capturer = CaptureOutput()
        capturer.start_capture()
        try:
            self.assertRaises(TypeError, capturer.start_capture)
        finally:
            # Make sure not to start swallowing output here ;-).
            capturer.finish_capture()
        # Nested Stream.redirect() calls should raise an exception.
        stream = Stream(sys.stdout.fileno())
        stream.redirect(sys.stderr.fileno())
        self.assertRaises(TypeError, stream.redirect, sys.stderr.fileno())

Example 34

Project: Ciao
Source File: ciaomcu.py
View license
	def write(self, status, message, data = None):
		output = [ str(status), str(message) ]
		if not data is None:
			data = utils.serialize(data)
			output.append(data.tostring())
		#4 (ASCII) means end trasmit (like newline but via a non-printable char)
		os.write(sys.stdout.fileno(), ";".join(output)+ chr(4))

Example 35

Project: python-deployer
Source File: socket_client.py
View license
def get_size():
    # Buffer for the C call
    buf = array.array('h', [0, 0, 0, 0 ])

    # Do TIOCGWINSZ (Get)
    fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, buf, True)

    # Return rows, cols
    return buf[0], buf[1]

Example 36

View license
def print_encoded(*args):
    """This will replace unsuitable characters and doesn't append a newline
    """
    stringArgs = ()
    for arg in args:
        stringArgs += encode(arg),
    msg = b" ".join(stringArgs)
    if not msg.endswith(b"\n"):
        msg += b" "
    if os.name == "nt":
        os.write(sys.stdout.fileno(), msg)
    else:
        try:
            sys.stdout.buffer.write(msg)
        except AttributeError:
            sys.stdout.write(msg)

Example 37

Project: bundlewrap
Source File: ui.py
View license
def term_width():
    if not TTY:
        return 0

    fd = sys.stdout.fileno()
    _, width = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, 'aaaa'))
    return width

Example 38

View license
def print_encoded(*args):
    """This will replace unsuitable characters and doesn't append a newline
    """
    stringArgs = ()
    for arg in args:
        stringArgs += encode(arg),
    msg = b" ".join(stringArgs)
    if not msg.endswith(b"\n"):
        msg += b" "
    if os.name == "nt":
        os.write(sys.stdout.fileno(), msg)
    else:
        try:
            sys.stdout.buffer.write(msg)
        except AttributeError:
            sys.stdout.write(msg)

Example 39

Project: raffaello
Source File: raffaello.py
View license
    def _manage_child(self, pipe_read, pipe_write):
        os.close(pipe_read)

        # redirect stdout to pipe in order to let
        #  parent process read
        os.dup2(pipe_write, sys.stdout.fileno())
        os.dup2(pipe_write, sys.stderr.fileno())

        # execute the command
        os.system(self.command)

Example 40

Project: sigal
Source File: log.py
View license
def init_logging(name, level=logging.INFO):
    """Logging config

    Set the level and create a more detailed formatter for debug mode.

    """
    logger = logging.getLogger(name)
    logger.setLevel(level)

    if os.isatty(sys.stdout.fileno()) and not sys.platform.startswith('win'):
        formatter = ColoredFormatter()
    elif level == logging.DEBUG:
        formatter = Formatter('%(levelname)s - %(message)s')
    else:
        formatter = Formatter('%(message)s')

    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logger.addHandler(handler)

Example 41

Project: reql_cli
Source File: __init__.py
View license
    @staticmethod
    def make(format, style, pagesize):
        '''Factory method to create the appropriate output'''
        is_atty = os.isatty(sys.stdout.fileno())
        if format == 'color' or format == 'auto' and is_atty:
            return ColorOutput(style, pagesize)
        elif format == 'newline' or format == 'auto' and not is_atty:
            return NewlineOutput()
        elif format == 'array':
            return ArrayOutput()
        else:
            raise Exception('{} {} {} is illegal!'.format(
                format, style, pagesize))

Example 42

Project: dxr
Source File: utils.py
View license
def open_log(folder, name, use_stdout=False):
    """Return a writable file-like object representing a log file.

    :arg folder: The folder to put the log file in
    :arg name: The name of the log file
    :arg use_stdout: If True, return a handle to stdout for verbose output,
        duplicated so it can be closed with impunity.

    """
    if use_stdout:
        return fdopen(dup(stdout.fileno()), 'w')
    return open(join(folder, name), 'w', 1)

Example 43

Project: parakeet
Source File: timer.py
View license
  def __enter__(self):
    if self.suppress_stdout:
      stdout_newfile = tempfile.NamedTemporaryFile()
      self.prev_stdout_fd = os.dup(sys.stdout.fileno())
      os.dup2(stdout_newfile.fileno(), sys.stdout.fileno())
      self.prev_stdout = sys.stdout
  
    if self.suppress_stderr:
      stderr_newfile = tempfile.NamedTemporaryFile()
      self.prev_stderr_fd = os.dup(sys.stderr.fileno())
      os.dup2(stderr_newfile.fileno(), sys.stderr.fileno())
      self.prev_stderr = sys.stderr 
    
    self.start_t = time.time()

Example 44

Project: llvm-p86
Source File: compiler.py
View license
    def save_bit_code(self, out, triple=''):

        if self.ctx is None or self.ctx.module is None:
            return

        tm = ee.TargetMachine.new(triple)
        self.ctx.module.target = str(tm.triple)
        self.ctx.module.data_layout = str(tm.target_data)

        bc = self.ctx.module.to_bitcode()

        if out == '-':
            os.write(sys.stdout.fileno(), bc)
        else:
            f = self._open_file(out)
            f.write(bc)
            f.close()

Example 45

Project: archivematica
Source File: upload-qubit.py
View license
def hilite(string, status=True):
    if not os.isatty(sys.stdout.fileno()):
        return string
    attr = []
    if status:
        attr.append('32')
    else:
        attr.append('31')
    return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)

Example 46

Project: dxr
Source File: utils.py
View license
def open_log(folder, name, use_stdout=False):
    """Return a writable file-like object representing a log file.

    :arg folder: The folder to put the log file in
    :arg name: The name of the log file
    :arg use_stdout: If True, return a handle to stdout for verbose output,
        duplicated so it can be closed with impunity.

    """
    if use_stdout:
        return fdopen(dup(stdout.fileno()), 'w')
    return open(join(folder, name), 'w', 1)

Example 47

Project: llvm-p86
Source File: compiler.py
View license
    def save_obj_code(self, out, triple='', cpu='', attrs=''):

        if self.ctx is None or self.ctx.module is None:
            return

        if not cpu: cpu = 'generic'

        tm = ee.TargetMachine.new(triple, cpu, attrs, 0)
        obj = tm.emit_object(self.ctx.module)

        if out == '-':
            os.write(sys.stdout.fileno(), obj)
        else:
            f = self._open_file(out)
            f.write(obj)
            f.close()

Example 48

Project: ntfy
Source File: terminal.py
View license
def darwin_terminal_shell_is_focused():
    focused_tty = osascript_tell(
        'Terminal',
        'tty of (first tab of (first window whose frontmost is true) '
        'whose selected is true)',
    )
    return focused_tty == ttyname(stdout.fileno())

Example 49

Project: bsd-cloudinit
Source File: service.py
View license
def _is_daemon():
    # The process group for a foreground process will match the
    # process group of the controlling terminal. If those values do
    # not match, or ioctl() fails on the stdout file handle, we assume
    # the process is running in the background as a daemon.
    # http://www.gnu.org/software/bash/manual/bashref.html#Job-Control-Basics
    try:
        is_daemon = os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno())
    except OSError as err:
        if err.errno == errno.ENOTTY:
            # Assume we are a daemon because there is no terminal.
            is_daemon = True
        else:
            raise
    except UnsupportedOperation:
        # Could not get the fileno for stdout, so we must be a daemon.
        is_daemon = True
    return is_daemon

Example 50

Project: natural
Source File: data.py
View license
def _termsize():
    '''
    Get the current terminal size, returns a ``(height, width)`` tuple.
    '''

    try:
        return struct.unpack(
            'hh',
            fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234')
        )
    except:
        return (
            int(os.environ.get('LINES', 25)),
            int(os.environ.get('COLUMNS', 80)),
        )