Пример #1
0
 def test_os_fpathconf(self):
     os = self.posix
     assert os.fpathconf(1, "PC_PIPE_BUF") >= 128
     with raises(OSError):
         os.fpathconf(-1, "PC_PIPE_BUF")
     with raises(ValueError):
         os.fpathconf(1, "##")
Пример #2
0
    def setUp(self):
        super(TestCaseCanon, self).setUp()

        self.echo = False
        if sys.platform.lower().startswith('linux'):
            # linux is 4096, N_TTY_BUF_SIZE.
            self.max_input = 4096
            self.echo = True
        elif sys.platform.lower().startswith('sunos'):
            # SunOS allows PC_MAX_CANON + 1; see
            # https://bitbucket.org/illumos/illumos-gate/src/d07a59219ab7fd2a7f39eb47c46cf083c88e932f/usr/src/uts/common/io/ldterm.c?at=default#cl-1888
            self.max_input = os.fpathconf(0, 'PC_MAX_CANON') + 1
        else:
            # All others (probably) limit exactly at PC_MAX_CANON
            self.max_input = os.fpathconf(0, 'PC_MAX_CANON')
Пример #3
0
    def __init__(self, path):

        self._f = open(path, "r+b")
        self._path_cache = {}
        self._path_max = fpathconf(self._f.fileno(), "PC_PATH_MAX")
        logger.info("PATH_MAX is %i", self._path_max)

        br = BootRecord.from_fileobj(self._f)
        assert br["ident"].rstrip("\0") == "clfs", repr(br["ident"])
        assert br["version"] == 1

        self.cluster_size = br["clrsize"]
        self.clno_count_per_atab_cluster = self.cluster_size // clno_t.size

        self.region_master_start = 0
        self.region_master_length = br["mstrclrs"]
        self.region_master_end = self.region_master_start + self.region_master_length

        self.region_atab_start = self.region_master_end
        self.region_atab_length = br["atabclrs"]
        self.region_atab_end = self.region_atab_start + self.region_atab_length

        self.region_data_start = self.region_atab_end
        self.region_data_length = br["dataclrs"]
        self.region_data_end = self.region_atab_start + self.region_data_length

        self.fs_cluster_count = \
                self.region_master_length \
                + self.region_atab_length \
                + self.region_data_length
        self.fs_total_byte_size = self.fs_cluster_count * self.cluster_size

        self._last_alloc_clno = self.region_data_end - 1
Пример #4
0
def get_defaults():
    """
    Returns a dictionary of variables and their possibly os-dependent defaults.
    
    """
    DEFAULTS = {}
    # Determine the run-time pipe read/write buffer.
    if 'PC_PIPE_BUF' in os.pathconf_names:
        # unix
        x, y = os.pipe()
        DEFAULTS['PIPE_BUF'] = os.fpathconf(x, "PC_PIPE_BUF")
    else:
        # in Jython 16384
        # on windows 512
        # in jython in windows 512
        DEFAULTS['PIPE_BUF'] = 512

    # Determine the run-time socket buffers.
    # Note that this number is determine on the papy server
    # and inherited by the clients.
    tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    DEFAULTS['TCP_SNDBUF'] = tcp_sock.getsockopt(socket.SOL_SOCKET, \
                                                 socket.SO_SNDBUF)
    DEFAULTS['TCP_RCVBUF'] = tcp_sock.getsockopt(socket.SOL_SOCKET, \
                                                 socket.SO_RCVBUF)
    udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    DEFAULTS['UDP_SNDBUF'] = udp_sock.getsockopt(socket.SOL_SOCKET, \
                                                 socket.SO_SNDBUF)
    DEFAULTS['UDP_RCVBUF'] = udp_sock.getsockopt(socket.SOL_SOCKET, \
                                                 socket.SO_RCVBUF)

    # check the ip visible from the world.
    DEFAULTS['WHATS_MYIP_URL'] = \
    'http://www.whatismyip.com/automation/n09230945.asp'
    return DEFAULTS
Пример #5
0
def setup_term():
    """
    Terminal initialization
    @return: Old terminal settings
    """

    term = term_settings()
    stdin = sys.stdin.fileno()

    if term is None:
        return None
    
    try:
        vdisable = os.fpathconf(stdin, "PC_VDISABLE")
    except ValueError:
        return

    _saved_term = copy.deepcopy(term[-1])

    # Disable special symbols
    _todisable = [getattr(termios, x) for x in ("VQUIT",     # ^\
                                                "VINTR",     # ^C
                                                "VSUSP",     # ^Z
                                                "VLNEXT",    # ^V
                                                "VSTART",    # ^Q
                                                "VSTOP",     # ^S
                                                "VDISCARD",  # ^O
                                                )]

    for _key in _todisable:
        term[-1][_key] = vdisable

    termios.tcsetattr(stdin, termios.TCSANOW, term)

    return _saved_term
Пример #6
0
def get_defaults():
    """
    Returns a dictionary of variables and their possibly os-dependent defaults.
    
    """
    DEFAULTS = {}
    # Determine the run-time pipe read/write buffer.
    if 'PC_PIPE_BUF' in os.pathconf_names:
        # unix
        x, y = os.pipe()
        DEFAULTS['PIPE_BUF'] = os.fpathconf(x, "PC_PIPE_BUF")
    else:
        # in Jython 16384
        # on windows 512
        # in jython in windows 512
        DEFAULTS['PIPE_BUF'] = 512

    # Determine the run-time socket buffers.
    # Note that this number is determine on the papy server
    # and inherited by the clients.
    tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    DEFAULTS['TCP_SNDBUF'] = tcp_sock.getsockopt(socket.SOL_SOCKET, \
                                                 socket.SO_SNDBUF)
    DEFAULTS['TCP_RCVBUF'] = tcp_sock.getsockopt(socket.SOL_SOCKET, \
                                                 socket.SO_RCVBUF)
    udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    DEFAULTS['UDP_SNDBUF'] = udp_sock.getsockopt(socket.SOL_SOCKET, \
                                                 socket.SO_SNDBUF)
    DEFAULTS['UDP_RCVBUF'] = udp_sock.getsockopt(socket.SOL_SOCKET, \
                                                 socket.SO_RCVBUF)

    # check the ip visible from the world.
    DEFAULTS['WHATS_MYIP_URL'] = \
    'http://www.whatismyip.com/automation/n09230945.asp'
    return DEFAULTS
Пример #7
0
def _get_pos_and_size(stdin, stdout):
    import termios
    stdin_fileno = stdin.fileno()
    vdisable = os.fpathconf(stdin_fileno, 'PC_VDISABLE')
    backup = termios.tcgetattr(stdin_fileno)
    new = termios.tcgetattr(stdin_fileno)
    new[3] &= ~(termios.ECHO | termios.ICANON)
    new[6][termios.VMIN] = 1
    new[6][termios.VTIME] = 0
    termios.tcsetattr(stdin_fileno, termios.TCSAFLUSH, new)
    try:
        position = _getposition(stdin, stdout)
        if position:
            y, x = position
            try:
                dimension = _getdimension_dtterm(stdin, stdout)
                if not dimension:
                    stdout.write("\x1b[9999;9999H")
                    dimension = _getposition(stdin, stdout)
                if dimension: 
                    row, col = dimension
                    return (row, col, y, x)
            finally:
                stdout.write("\033[%d;%dH" % (y, x))
    finally:
        termios.tcsetattr(stdin_fileno, termios.TCSAFLUSH, backup)
    return None
Пример #8
0
 def test_communicate_pipe_buf(self):
     # communicate() with writes larger than pipe_buf
     # This test will probably deadlock rather than fail, if
     # communicate() does not work properly.
     x, y = os.pipe()
     if mswindows:
         pipe_buf = 512
     else:
         pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
     os.close(x)
     os.close(y)
     p = subprocess.Popen([
         sys.executable, "-c",
         'import sys,os;'
         'sys.stdout.write(sys.stdin.read(47));'
         'sys.stderr.write("xyz"*%d);'
         'sys.stdout.write(sys.stdin.read())' % pipe_buf
     ],
                          stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE)
     self.addCleanup(p.stdout.close)
     self.addCleanup(p.stderr.close)
     self.addCleanup(p.stdin.close)
     string_to_write = "abc" * pipe_buf
     (stdout, stderr) = p.communicate(string_to_write)
     self.assertEqual(stdout, string_to_write)
 def test_communicate_pipe_buf(self):
     # communicate() with writes larger than pipe_buf
     # This test will probably deadlock rather than fail, if
     # communicate() does not work properly.
     x, y = os.pipe()
     if mswindows:
         pipe_buf = 512
     else:
         pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
     os.close(x)
     os.close(y)
     p = subprocess.Popen([sys.executable, "-c",
                           'import sys,os;'
                           'sys.stdout.write(sys.stdin.read(47));'
                           'sys.stderr.write("xyz"*%d);'
                           'sys.stdout.write(sys.stdin.read())' % pipe_buf],
                          stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE)
     self.addCleanup(p.stdout.close)
     self.addCleanup(p.stderr.close)
     self.addCleanup(p.stdin.close)
     string_to_write = b"abc"*pipe_buf
     (stdout, stderr) = p.communicate(string_to_write)
     self.assertEqual(stdout, string_to_write)
Пример #10
0
    def __init__(self, path):

        self._f = open(path, "r+b")
        self._path_cache = {}
        self._path_max = fpathconf(self._f.fileno(), "PC_PATH_MAX")
        logger.info("PATH_MAX is %i", self._path_max)

        br = BootRecord.from_fileobj(self._f)
        assert br["ident"].rstrip("\0") == "clfs", repr(br["ident"])
        assert br["version"] == 1

        self.cluster_size = br["clrsize"]
        self.clno_count_per_atab_cluster = self.cluster_size // clno_t.size

        self.region_master_start = 0
        self.region_master_length = br["mstrclrs"]
        self.region_master_end = self.region_master_start + self.region_master_length

        self.region_atab_start = self.region_master_end
        self.region_atab_length = br["atabclrs"]
        self.region_atab_end = self.region_atab_start + self.region_atab_length

        self.region_data_start = self.region_atab_end
        self.region_data_length = br["dataclrs"]
        self.region_data_end = self.region_atab_start + self.region_data_length

        self.fs_cluster_count = \
                self.region_master_length \
                + self.region_atab_length \
                + self.region_data_length
        self.fs_total_byte_size = self.fs_cluster_count * self.cluster_size

        self._last_alloc_clno = self.region_data_end - 1
Пример #11
0
def display_fpathconf():
    DISP_VALUES = (
        ('PC_MAX_CANON', ('Max no. of bytes in a '
                          'terminal canonical input line.')),
        ('PC_MAX_INPUT', ('Max no. of bytes for which '
                          'space is available in a terminal input queue.')),
        ('PC_PIPE_BUF', ('Max no. of bytes which will '
                         'be written atomically to a pipe.')),
        ('PC_VDISABLE', 'Terminal character disabling value.')
    )
    FMT = '{name:<13} {value:<5} {description}'

    # column header
    print(FMT.format(name='name', value='value', description='description'))
    print(FMT.format(name=('-' * 13), value=('-' * 5), description=('-' * 11)))

    fd = sys.stdin.fileno()
    for name, description in DISP_VALUES:
        key = os.pathconf_names.get(name, None)
        if key is None:
            value = 'UNDEF'
        else:
            try:
                value = os.fpathconf(fd, name)
            except OSError as err:
                value = 'OSErrno {0.errno}'.format(err)
        if name == 'PC_VDISABLE':
            value = hex(value)
        print(FMT.format(name=name, value=value, description=description))
    print()
Пример #12
0
def fpathconf(space, fd, w_name):
    num = confname_w(space, w_name, os.pathconf_names)
    try:
        res = os.fpathconf(fd, num)
    except OSError as e:
        raise wrap_oserror(space, e)
    return space.wrap(res)
Пример #13
0
    def testLineReader(self):
        p = os.pipe()
        pipeSize = os.fpathconf(p[0], os.pathconf_names['PC_PIPE_BUF'])

        rdr = util.LineReader(p[0])
        writeFd = p[1]

        os.write(writeFd, "hel")
        assert(rdr.readlines() == [ ])
        os.write(writeFd, "lo\n")
        assert(rdr.readlines() == [ "hello\n" ])

        os.write(writeFd, "hello\nworld\n")
        assert(rdr.readlines() == [ "hello\n", "world\n" ])

        os.write(writeFd, "hello\nthere")
        assert(rdr.readlines() == [ "hello\n" ])
        os.write(writeFd, "\nbig")
        assert(rdr.readlines() == [ "there\n" ])
        os.write(writeFd, "\nwide\nworld\n")
        assert(rdr.readlines() == [ "big\n", "wide\n", "world\n" ])

        os.close(writeFd)
        assert(rdr.readlines() == None )

        os.close(p[0])
Пример #14
0
def _get_pos_and_size(stdin, stdout):
    import termios
    stdin_fileno = stdin.fileno()
    vdisable = os.fpathconf(stdin_fileno, 'PC_VDISABLE')
    backup = termios.tcgetattr(stdin_fileno)
    new = termios.tcgetattr(stdin_fileno)
    new[3] &= ~(termios.ECHO | termios.ICANON)
    new[6][termios.VMIN] = 1
    new[6][termios.VTIME] = 0
    termios.tcsetattr(stdin_fileno, termios.TCSAFLUSH, new)
    try:
        position = _getposition(stdin, stdout)
        if position:
            y, x = position
            try:
                dimension = _getdimension_dtterm(stdin, stdout)
                if not dimension:
                    stdout.write("\x1b[9999;9999H")
                    dimension = _getposition(stdin, stdout)
                if dimension:
                    row, col = dimension
                    return (row, col, y, x)
            finally:
                stdout.write("\033[%d;%dH" % (y, x))
    finally:
        termios.tcsetattr(stdin_fileno, termios.TCSAFLUSH, backup)
    return None
Пример #15
0
def main():
    """Program entry point."""
    fd = sys.stdin.fileno()
    locale.setlocale(locale.LC_ALL, '')
    encoding = locale.getpreferredencoding()

    print('os.isatty({0}) => {1}'.format(fd, os.isatty(fd)))
    print('locale.getpreferredencoding() => {0}'.format(encoding))

    display_pathconf(names=os.pathconf_names,
                     getter=lambda name: os.fpathconf(fd, name))

    try:
        (iflag, oflag, cflag, lflag,
         _, _,  # input / output speed (bps macros)
         ctlc) = termios.tcgetattr(fd)
    except termios.error as err:
        print('stdin is not a typewriter: {0}'.format(err))
    else:
        display_bitmask(kind='  Input Mode',
                        bitmap=BITMAP_IFLAG,
                        value=iflag)
        display_bitmask(kind=' Output Mode',
                        bitmap=BITMAP_OFLAG,
                        value=oflag)
        display_bitmask(kind='Control Mode',
                        bitmap=BITMAP_CFLAG,
                        value=cflag)
        display_bitmask(kind='  Local Mode',
                        bitmap=BITMAP_LFLAG,
                        value=lflag)
        display_ctl_chars(index=CTLCHAR_INDEX,
                          ctlc=ctlc)
        print('os.ttyname({0}) => {1}'.format(fd, os.ttyname(fd)))
        print('os.ctermid() => {0}'.format(os.ttyname(fd)))
Пример #16
0
def fpathconf(space, fd, w_name):
    num = confname_w(space, w_name, os.pathconf_names)
    try:
        res = os.fpathconf(fd, num)
    except OSError as e:
        raise wrap_oserror(space, e)
    return space.newint(res)
Пример #17
0
    def testLineReader(self):
        p = os.pipe()
        pipeSize = os.fpathconf(p[0], os.pathconf_names['PC_PIPE_BUF'])

        rdr = util.LineReader(p[0])
        writeFd = p[1]

        os.write(writeFd, "hel")
        assert(rdr.readlines() == [ ])
        os.write(writeFd, "lo\n")
        assert(rdr.readlines() == [ "hello\n" ])

        os.write(writeFd, "hello\nworld\n")
        assert(rdr.readlines() == [ "hello\n", "world\n" ])

        os.write(writeFd, "hello\nthere")
        assert(rdr.readlines() == [ "hello\n" ])
        os.write(writeFd, "\nbig")
        assert(rdr.readlines() == [ "there\n" ])
        os.write(writeFd, "\nwide\nworld\n")
        assert(rdr.readlines() == [ "big\n", "wide\n", "world\n" ])

        os.close(writeFd)
        assert(rdr.readlines() == None )

        os.close(p[0])
Пример #18
0
def main():
    fd = sys.stdin.fileno()
    locale.setlocale(locale.LC_ALL, "")
    encoding = locale.getpreferredencoding()

    print("os.isatty({0}) => {1}".format(fd, os.isatty(fd)))
    print("locale.getpreferredencoding() => {0}".format(encoding))

    display_conf(
        kind="pathconf",
        names=os.pathconf_names,
        getter=lambda name: os.fpathconf(fd, name),
    )

    try:
        (iflag, oflag, cflag, lflag, ispeed, ospeed, cc) = termios.tcgetattr(fd)
    except termios.error as err:
        print("stdin is not a typewriter: {0}".format(err))
    else:
        display_bitmask(kind="Input Mode", bitmap=BITMAP_IFLAG, value=iflag)
        display_bitmask(kind="Output Mode", bitmap=BITMAP_OFLAG, value=oflag)
        display_bitmask(kind="Control Mode", bitmap=BITMAP_CFLAG, value=cflag)
        display_bitmask(kind="Local Mode", bitmap=BITMAP_LFLAG, value=lflag)
        display_ctl_chars(index=CTLCHAR_INDEX, cc=cc)
        try:
            print("os.ttyname({0}) => {1}".format(fd, os.ttyname(fd)))
            print("os.ctermid() => {0}".format(os.ctermid()))
        except OSError as e:
            # Travis fails on ttyname with errno 0 'Error'.
            print("Error inspecting TTY: {0}".format(e))
Пример #19
0
def main():
    """Program entry point."""
    fd = sys.stdin.fileno()
    locale.setlocale(locale.LC_ALL, '')
    encoding = locale.getpreferredencoding()

    print('os.isatty({0}) => {1}'.format(fd, os.isatty(fd)))
    print('locale.getpreferredencoding() => {0}'.format(encoding))

    display_pathconf(names=os.pathconf_names,
                     getter=lambda name: os.fpathconf(fd, name))

    try:
        (
            iflag,
            oflag,
            cflag,
            lflag,
            _,
            _,  # input / output speed (bps macros)
            ctlc) = termios.tcgetattr(fd)
    except termios.error as err:
        print('stdin is not a typewriter: {0}'.format(err))
    else:
        display_bitmask(kind='  Input Mode', bitmap=BITMAP_IFLAG, value=iflag)
        display_bitmask(kind=' Output Mode', bitmap=BITMAP_OFLAG, value=oflag)
        display_bitmask(kind='Control Mode', bitmap=BITMAP_CFLAG, value=cflag)
        display_bitmask(kind='  Local Mode', bitmap=BITMAP_LFLAG, value=lflag)
        display_ctl_chars(index=CTLCHAR_INDEX, ctlc=ctlc)
        print('os.ttyname({0}) => {1}'.format(fd, os.ttyname(fd)))
        print('os.ctermid() => {0}'.format(os.ttyname(fd)))
Пример #20
0
        def Say(text):
            if len(text) + 1 > os.fpathconf(pw, "PC_PIPE_BUF"):
                # This should never happen.  POSIX guarantees that at least
                # 512 bytes can be sent atomically, and we only ever need
                # to send dotted decimal IPv4 addresses and short error
                # messages.  Neither of those should be anywhere near
                # the limit.
                Fatal("Message is too long for pipe atomicity")

            print >> p, text
Пример #21
0
        def Say( text ):
            if len( text ) + 1 > os.fpathconf( pw, "PC_PIPE_BUF" ):
                # This should never happen.  POSIX guarantees that at least
                # 512 bytes can be sent atomically, and we only ever need
                # to send dotted decimal IPv4 addresses and short error
                # messages.  Neither of those should be anywhere near
                # the limit.
                Fatal( "Message is too long for pipe atomicity" )

            print >> p, text
Пример #22
0
Файл: tff.py Проект: lurdan/tff
    def __setupterm(self, fd):
        term = termios.tcgetattr(fd)

        ## c_iflag
        #IUTF8 = 16384
        term[0] &= ~(termios.IGNBRK
                     | termios.BRKINT
                     | termios.PARMRK
                     | termios.ISTRIP
                     | termios.INLCR
                     | termios.IGNCR
                     | termios.ICRNL
                     | termios.IXON)

        term[1] &= ~(termios.OPOST
                     | termios.ONLCR)

        # c_cflag
        c_cflag = term[2]
        c_cflag &= ~(termios.CSIZE | termios.PARENB)
        c_cflag |= termios.CS8
        term[2] = c_cflag

        ## c_lflag
        c_lflag = term[3]
        c_lflag &= ~(termios.ECHO
                     | termios.ECHONL
                     | termios.ICANON
                     | termios.ISIG
                     | termios.IEXTEN)
        term[3] = c_lflag

        # c_cc
        # this PTY is jast a filter, so it must not fire signals
        vdisable = os.fpathconf(self._stdin_fileno, 'PC_VDISABLE')
        VDSUSP = 11
        c_cc = term[6]
        c_cc[termios.VEOF] = vdisable  # Ctrl-D
        c_cc[termios.VINTR] = vdisable  # Ctrl-C
        c_cc[termios.VREPRINT] = vdisable  # Ctrl-R
        c_cc[termios.VSTART] = vdisable  # Ctrl-Q
        c_cc[termios.VSTOP] = vdisable  # Ctrl-S
        c_cc[termios.VLNEXT] = vdisable  # Ctrl-V
        c_cc[termios.VWERASE] = vdisable  # Ctrl-W
        c_cc[termios.VKILL] = vdisable  # Ctrl-X
        c_cc[termios.VSUSP] = vdisable  # Ctrl-Z
        c_cc[termios.VQUIT] = vdisable  # Ctrl-\
        c_cc[VDSUSP] = vdisable  # Ctrl-Y

        termios.tcsetattr(fd, termios.TCSANOW, term)
Пример #23
0
def display_fpathconf():
    """Program entry point."""

    if not hasattr(os, "pathconf_names"):
        return

    disp_values = (
        ('PC_MAX_CANON', ('Max no. of bytes in a '
                          'terminal canonical input line.')),
        ('PC_MAX_INPUT', ('Max no. of bytes for which '
                          'space is available in a terminal input queue.')),
        ('PC_PIPE_BUF', ('Max no. of bytes which will '
                         'be written atomically to a pipe.')),

        # to explain in more detail: PC_VDISABLE is the reference character in
        # the pairing output for bin/display-terminalinfo.py: if the value
        # matches (\xff), then that special control character is disabled, fe:
        #
        #          Index Name    Special Character    Default Value
        #          VEOF          EOF                  ^D
        #          VEOL          EOL                  _POSIX_VDISABLE
        #
        # irregardless, this value is almost always \xff.
        ('PC_VDISABLE', 'Terminal character disabling value.'))
    fmt = '{name:<13} {value:<10} {description:<11}'

    # column header
    print(fmt.format(name='name', value='value', description='description'))
    print(fmt.replace('<', '-<').format(name='-', value='-', description='-'))

    fd = sys.stdin.fileno()
    for name, description in disp_values:
        key = os.pathconf_names.get(name, None)
        if key is None:
            value = 'UNDEF'
        else:
            try:
                value = os.fpathconf(fd, name)
                if name == 'PC_VDISABLE':
                    value = r'\x{0:02x}'.format(value)
            except OSError as err:
                value = 'OSErrno {0.errno}'.format(err)

        print(fmt.format(name=name, value=value, description=description))
    print()
Пример #24
0
    def _start_magma(self):
        # Signal handlers are inherited by forked processes, and we can't easily
        # reset it from the subprocess. Since kernelapp ignores SIGINT except in
        # message handlers, we need to temporarily reset the SIGINT handler here
        # so that magma and its children are interruptible.
        sig = signal.signal(signal.SIGINT, signal.SIG_DFL)
        try:
            magma = spawn(
                "magma",
                echo=False,
                encoding="utf-8",
                maxread=4194304,
                ignore_sighup=True,
                codec_errors="ignore",
            )
            magma.expect_exact("> ")
            banner = magma.before
            magma.sendline("SetColumns(0);")
            magma.expect_exact("> ")
            magma.sendline("SetAutoColumns(false);")
            magma.expect_exact("> ")
            magma.sendline("SetLineEditor(false);")
            magma.expect_exact("> ")
            magma.sendline(f'SetPrompt("{self._prompt}");')
            magma.expect_exact(self._prompt)
            self.child = magma
        finally:
            signal.signal(signal.SIGINT, sig)

        # figure out the maximum length of a formatted input line
        try:
            # Linux 4096
            # OSX 1024
            # Solaris 256
            self.max_input_line_size = (
                int(fpathconf(self.child.child_fd, "PC_MAX_CANON")) - 1)
        except OSError:
            # if we can't compute the PTY limit take something minimum that we are aware of
            self.max_input_line_size = 255
        lang_version = re.search(r"Magma V(\d*.\d*-\d*)", banner).group(1)
        self.banner = "Magma kernel connected to Magma " + lang_version
        self.language_info["version"] = lang_version
        self.language_version = lang_version
Пример #25
0
def display_fpathconf():
    """Program entry point."""
    disp_values = (
        ('PC_MAX_CANON', ('Max no. of bytes in a '
                          'terminal canonical input line.')),
        ('PC_MAX_INPUT', ('Max no. of bytes for which '
                          'space is available in a terminal input queue.')),
        ('PC_PIPE_BUF', ('Max no. of bytes which will '
                         'be written atomically to a pipe.')),

        # to explain in more detail: PC_VDISABLE is the reference character in
        # the pairing output for bin/display-terminalinfo.py: if the value
        # matches (\xff), then that special control character is disabled, fe:
        #
        #          Index Name    Special Character    Default Value
        #          VEOF          EOF                  ^D
        #          VEOL          EOL                  _POSIX_VDISABLE
        #
        # irregardless, this value is almost always \xff.
        ('PC_VDISABLE', 'Terminal character disabling value.')
    )
    fmt = '{name:<13} {value:<10} {description:<11}'

    # column header
    print(fmt.format(name='name', value='value', description='description'))
    print(fmt.replace('<', '-<').format(name='-', value='-', description='-'))

    fd = sys.stdin.fileno()
    for name, description in disp_values:
        key = os.pathconf_names.get(name, None)
        if key is None:
            value = 'UNDEF'
        else:
            try:
                value = os.fpathconf(fd, name)
                if name == 'PC_VDISABLE':
                    value = r'\x{0:02x}'.format(value)
            except OSError as err:
                value = 'OSErrno {0.errno}'.format(err)

        print(fmt.format(name=name, value=value, description=description))
    print()
Пример #26
0
def main():
    fd = sys.stdin.fileno()
    locale.setlocale(locale.LC_ALL, '')
    encoding = locale.getpreferredencoding()

    print('os.isatty({0}) => {1}'.format(fd, os.isatty(fd)))
    print('locale.getpreferredencoding() => {0}'.format(encoding))

    display_conf(kind='pathconf',
                 names=os.pathconf_names,
                 getter=lambda name: os.fpathconf(fd, name))

    try:
        (iflag, oflag, cflag, lflag, ispeed, ospeed, cc
         ) = termios.tcgetattr(fd)
    except termios.error as err:
        print('stdin is not a typewriter: {0}'.format(err))
    else:
        display_bitmask(kind='Input Mode',
                        bitmap=BITMAP_IFLAG,
                        value=iflag)
        display_bitmask(kind='Output Mode',
                        bitmap=BITMAP_OFLAG,
                        value=oflag)
        display_bitmask(kind='Control Mode',
                        bitmap=BITMAP_CFLAG,
                        value=cflag)
        display_bitmask(kind='Local Mode',
                        bitmap=BITMAP_LFLAG,
                        value=lflag)
        display_ctl_chars(index=CTLCHAR_INDEX,
                          cc=cc)
        try:
            print('os.ttyname({0}) => {1}'.format(fd, os.ttyname(fd)))
            print('os.ctermid() => {0}'.format(os.ctermid()))
        except OSError as e:
            # Travis fails on ttyname with errno 0 'Error'.
            print("Error inspecting TTY: {0}".format(e))
Пример #27
0
def display_fpathconf():
    DISP_VALUES = (
        ("PC_MAX_CANON", ("Max no. of bytes in a "
                          "terminal canonical input line.")),
        (
            "PC_MAX_INPUT",
            ("Max no. of bytes for which "
             "space is available in a terminal input queue."),
        ),
        (
            "PC_PIPE_BUF",
            ("Max no. of bytes which will "
             "be written atomically to a pipe."),
        ),
        ("PC_VDISABLE", "Terminal character disabling value."),
    )
    FMT = "{name:<13} {value:<5} {description}"

    # column header
    print(FMT.format(name="name", value="value", description="description"))
    print(FMT.format(name=("-" * 13), value=("-" * 5), description=("-" * 11)))

    fd = sys.stdin.fileno()
    for name, description in DISP_VALUES:
        key = os.pathconf_names.get(name, None)
        if key is None:
            value = "UNDEF"
        else:
            try:
                value = os.fpathconf(fd, name)
            except OSError as err:
                value = "OSErrno {0.errno}".format(err)
        if name == "PC_VDISABLE":
            value = hex(value)
        print(FMT.format(name=name, value=value, description=description))
    print()
Пример #28
0
 def test_os_fpathconf(self):
     os = self.posix
     assert os.fpathconf(1, "PC_PIPE_BUF") >= 128
     raises(OSError, os.fpathconf, -1, "PC_PIPE_BUF")
     raises(ValueError, os.fpathconf, 1, "##")
os.chflags(path, flags)         # 设置路径的标记为数字标记。
os.chmod(path, mode)            # 更改权限
os.chown(path, uid, gid)        # 更改文件所有者
os.chroot(path)                 # 改变当前进程的根目录
os.close(fd)                    # 关闭文件描述符 fd
os.closerange(fd_low, fd_high)  # 关闭所有文件描述符,从 fd_low (包含) 到 fd_high (不包含), 错误会忽略
os.curdir                       # 返回当前目录:('.')
os.dup(fd)                      # 复制文件描述符 fd
os.dup2(fd, fd2)                # 将一个文件描述符 fd 复制到另一个 fd2
os.environ                      # 获取系统环境变量
os.fchdir(fd)                   # 通过文件描述符改变当前工作目录
os.fchmod(fd, mode)             # 改变一个文件的访问权限,该文件由参数fd指定,参数mode是Unix下的文件访问权限。
os.fchown(fd, uid, gid)         # 修改一个文件的所有权,这个函数修改一个文件的用户ID和用户组ID,该文件由文件描述符fd指定。
os.fdatasync(fd)                # 强制将文件写入磁盘,该文件由文件描述符fd指定,但是不强制更新文件的状态信息。
os.fdopen(fd[, mode[, bufsize]])  # 通过文件描述符 fd 创建一个文件对象,并返回这个文件对象
os.fpathconf(fd, name)          # 返回一个打开的文件的系统配置信息。name为检索的系统配置的值,它也许是一个定义系统值的字符串,这些名字在很多标准中指定(POSIX.1, Unix 95, Unix 98, 和其它)。
os.fstat(fd)                    # 返回文件描述符fd的状态,像stat()。
os.fstatvfs(fd)                 # 返回包含文件描述符fd的文件的文件系统的信息,像 statvfs()
os.fsync(fd)                    # 强制将文件描述符为fd的文件写入硬盘。
os.ftruncate(fd, length)        # 裁剪文件描述符fd对应的文件, 所以它最大不能超过文件大小。
os.getcwd()                     # 返回当前工作目录
os.getcwdu()                    # 返回一个当前工作目录的Unicode对象
os.isatty(fd)                   # 如果文件描述符fd是打开的,同时与tty(-like)设备相连,则返回true, 否则False。
os.lchflags(path, flags)        # 设置路径的标记为数字标记,类似 chflags(),但是没有软链接
os.lchmod(path, mode)           # 修改连接文件权限
os.lchown(path, uid, gid)       # 更改文件所有者,类似 chown,但是不追踪链接。
os.link(src, dst)               # 创建硬链接,名为参数 dst,指向参数 src
os.listdir(path)                # 返回path指定的文件夹包含的文件或文件夹的名字的列表。
os.lseek(fd, pos, how)          # 设置文件描述符 fd当前位置为pos, how方式修改: SEEK_SET 或者 0 设置从文件开始的计算的pos; SEEK_CUR或者 1 则从当前位置计算; os.SEEK_END或者2则从文件尾部开始. 在unix,Windows中有效
os.lstat(path)                  # 像stat(),但是没有软链接
os.linesep                      # 当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
Пример #30
0
 def test_os_fpathconf(self):
     os = self.posix
     assert os.fpathconf(1, "PC_PIPE_BUF") >= 128
     raises(OSError, os.fpathconf, -1, "PC_PIPE_BUF")
     raises(ValueError, os.fpathconf, 1, "##")
Пример #31
0
#!usr/bin/python3
import os,sys

# 打开文件
fd = os.open('pathconf.txt',os.O_RDWR | os.O_CREAT)

print('%s'%os.pathconf_names)

# 获取文件最大连接数
no = os.fpathconf(fd,'PC_LINK_MAX')
print('Maximum number of links to the file. :%d'%no)

# 获取文件名最大长度
len = os.fpathconf(fd,"PC_NAME_MAX")
print('Maximum length of a fileName :%d'%len)

# 关闭文件
os.close(fd)

print('关闭文件成功')
Пример #32
0
)
from chroma_agent.utils import lsof
from chroma_agent.agent_client import (
    CryptoClient,
    ExceptionCatchingThread,
    HttpError,
    MAX_BYTES_PER_POST,
    MIN_SESSION_BACKOFF,
    MAX_SESSION_BACKOFF,
)
from iml_common.lib.date_time import IMLDateTime
from iml_common.lib.date_time import FixedOffset

READER_SELECT_TIMEOUT = 1.0
RELAY_POLL_INTERVAL = 1
BUFSIZ = os.fpathconf(1, "PC_PIPE_BUF")
COPYTOOL_PROGRESS_INTERVAL = 5  # default 30, increase for snappier UI


class CopytoolException(Exception):
    pass


class FifoReaderConflict(CopytoolException):
    def __init__(self, pids):
        self.pids = pids

    def __str__(self):
        return "Failed to start FIFO reader due to other readers: %s" % ",".join(
            self.pids)
Пример #33
0
import select
import json

from argparse import ArgumentParser, ArgumentError, Action

from chroma_agent import config
from chroma_agent.crypto import Crypto
from chroma_agent.log import copytool_log, copytool_log_setup, increase_loglevel, decrease_loglevel
from chroma_agent.utils import lsof
from chroma_agent.agent_client import CryptoClient, ExceptionCatchingThread, HttpError, MAX_BYTES_PER_POST, MIN_SESSION_BACKOFF, MAX_SESSION_BACKOFF
from iml_common.lib.date_time import IMLDateTime
from iml_common.lib.date_time import FixedOffset

READER_SELECT_TIMEOUT = 1.0
RELAY_POLL_INTERVAL = 1
BUFSIZ = os.fpathconf(1, 'PC_PIPE_BUF')
COPYTOOL_PROGRESS_INTERVAL = 5  # default 30, increase for snappier UI


class CopytoolException(Exception):
    pass


class FifoReaderConflict(CopytoolException):
    def __init__(self, pids):
        self.pids = pids

    def __str__(self):
        return "Failed to start FIFO reader due to other readers: %s" % ",".join(
            self.pids)
Пример #34
0
# @copyright by hoojo@2018
# @changelog Added python3 `os file -> fpathconf` example

import os
'''
概述
    os.pathconf() 方法用于返回一个打开的文件的系统配置信息。
    Unix 平台下可用。
    
语法
    fpathconf()方法语法格式如下:
    os.fpathconf(fd, name)
    
参数
    name -- 文件描述符
    name -- 检索的系统配置的值,它也许是一个定义系统值的字符串,这些名字在很多标准中指定(POSIX.1, Unix 95, Unix 98, 和其它)。一些平台也定义了一些额外的名字。这些名字在主操作系统上pathconf_names的字典中。对于不在pathconf_names中的配置变量,传递一个数字作为名字,也是可以接受的。

返回值
        返回文件的系统信息。
'''
import os

# 打开文件
fd = os.open('/tmp/foo.txt', os.O_RDWR | os.O_CREAT)

print('pathconf_names: %s' % os.pathconf_names)

# 最大连接数
print('最大连接数:%s' % os.fpathconf(fd, 'PC_LINK_MAX'))

os.close(fd)
Пример #35
0
os.fchdir(fd)
# 通过文件描述符改变当前工作目录

os.fchmod(fd,mode)
# 改变一个文件的访问权限,该文件由参数fd指定,参数mode是Unix下的文件访问权限

os.fchown(fd,uid,gid)
# 修改一个文件的所有权,这个函数修改一个文件的用户ID和用户组ID,该文件由文件描述符fd指定

os.fdatasync(fd)
# 强制将文件谢谢如磁盘,该文件由文件描述符fd指定,但是不强制更新文件的状态信息

os.fdopen(fd[,mode[,bufsize]])
# 通过文件描述符fd创建一个文件独享,并返回这个文件对象

os.fpathconf(fd,name)
# 返回一个打开的文件的系统配置信息。name为检索的系统配置的值,它也许是一个定义系统值的字符串,这些名字在很多标准中指定(POSIX.1, Unix 95, Unix 98, 和其它)。

os.fstat(fd)
# 返回文件描述符fd的状态,像stat()

os.fstatvfs(fd)
# 返回包含文件描述符fd的文件的文件系统的信息,想stavfs()

os.fsync(fd)
# 强制将文件描述符为fd的文件写入硬盘

os.ftruncate(fd,length)
# 裁剪文件描述符fd对应的文件,所以它最大不能超过文件大小

os.isatty(fd)
Пример #36
0
import os
'''
概述
    os.fpathconf() 方法用于返回一个打开的文件的系统配置信息。
    Unix上可用。

语法
    fpathconf()方法语法格式如下:
    os.fpathconf(fd, name)
    
参数
    fd -- 打开的文件的描述符。
    name -- 可选,和buffersize参数和Python内建的open函数一样,mode参数可以指定『r,w,a,r+,w+,a+,b』等,表示文件的是只读的还是可以读写的,以及打开文件是以二进制还是文本形式打开。这些参数和C语言中的<stdio.h>中fopen函数中指定的mode参数类似。
    bufsize -- 检索的系统配置的值,它也许是一个定义系统值的字符串,这些名字在很多标准中指定(POSIX.1, Unix 95, Unix 98, 和其它)。一些平台也定义了一些额外的名字。这些名字在主操作系统上pathconf_names的字典中。对于不在pathconf_names中的配置变量,传递一个数字作为名字,也是可以接受的。

返回值
        返回一个打开的文件的系统配置信息
'''

# 打开文件
fd = os.open('/tmp/foo.txt', os.O_CREAT | os.O_RDWR)

# 配置名称列表
print('配置名称列表: %s' % os.pathconf_names)

print('文件最大连接数:%d' % os.fpathconf(fd, 'PC_LINK_MAX'))

print('文件名最大长度:%d' % os.fpathconf(fd, 'PC_NAME_MAX'))

os.close(fd)
Пример #37
0
# 读取内容
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print "Read String is : ", str
# 获取当前位置
print "Current I/O pointer position :%d" % fo.tell()
# 关闭文件
os.close(fd)

# 16 os.fpathconf(fd, name)
# 返回一个打开的文件的系统配置信息。name为检索的系统配置的值,它也许是一个定义系统值的字符串,这些名字在很多标准中指定(POSIX.1, Unix 95, Unix 98, 和其它)。
# 打开文件
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
print "%s" % os.pathconf_names
# 获取最大文件连接数
no = os.fpathconf(fd, 'PC_LINK_MAX')
print "文件最大连接数为 :%d" % no
# 获取文件名最大长度
no = os.fpathconf(fd, 'PC_NAME_MAX')
print "文件名最大长度为 :%d" % no
# 关闭文件
os.close(fd)

# 17 os.fstat(fd)
# 返回文件描述符fd的状态,像stat()。
# 打开文件
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# 获取元组
info = os.fstat(fd)
print "文件信息 :", info
# 获取文件 uid
Пример #38
0
def fpathconf(space, fd, w_name):
    num = confname_w(space, w_name, os.pathconf_names)
    try:
        return space.wrap(os.fpathconf(fd, num))
    except OSError, e:
        raise wrap_oserror(space, e)