示例#1
0
def at_probe():
    found = []
    if environment == 'linux':
        print('Probing for ttyACM devices...')
        for i in range(10):
            devname = '/dev/ttyACM%d' % i
            if not os.path.exists(devname):
                continue
            mode = os.stat(devname).st_mode
            if S_ISCHR(mode):
                found += [devname]

    elif environment == 'windows':
        print('Probing for COM ports...')
        for i in range(256):
            port = 'COM%d' % i
            try:
                s = serial.Serial(port)
                s.close()
                found.append(port)
            except (OSError, serial.SerialException):
                pass
    else:
        raise Exception('EnvironmentError: unknow OS')
    return found
示例#2
0
    def inode_type(self, inode, symtab, addr_space):
        imode = inode.m('i_mode').v()

        type = "UNKN"

        if S_ISREG(imode):
            type = "REG"
        elif S_ISLNK(imode):
            type = "LNK"
        elif S_ISCHR(imode):
            type = "CHR"
        elif S_ISBLK(imode):
            type = "BLK"
        elif S_ISDIR(imode):
            type = "DIR"
        elif S_ISSOCK(imode):
            type = "SOCK"
        elif S_ISFIFO(imode):
            type = "FIFO"
            if symtab.lookup("rdwr_pipe_fops"):
                i_fop_offset = inode.get_member_offset('i_fop')
                if i_fop_offset > 0:

                    i_fop = inode.get_member('i_fop').v()

                    if i_fop == symtab.lookup("rdwr_pipe_fops"):
                        type = "PIPE"
        return type
示例#3
0
def is_block(fthing):
    """Take in a file object and checks to see if it's a block or fifo."""
    if fthing is sys.stdout or fthing is sys.stdin:
        return True
    else:
        mode = os.stat(fthing.name).st_mode
        return S_ISBLK(mode) or S_ISCHR(mode)
示例#4
0
def format_device(mode, major, minor):
    if S_ISCHR(mode):
        kind = 'character'
    elif S_ISBLK(mode):
        kind = 'block'
    else:
        kind = 'weird'
    return 'device:%s\nmajor: %d\nminor: %d\n' % (kind, major, minor)
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('device', help='Serial port device e.g. /dev/ttyS1')
    parser.add_argument('--baudrate', default=9600, type=int)
    parser.add_argument('--bytesize',
                        choices=[5, 6, 7, 8],
                        type=int,
                        help='set bytesize, one of {5, 6, 7, 8}, default: 8',
                        default=8)
    parser.add_argument('--parity',
                        choices=['N', 'E', 'O', 'S', 'M'],
                        type=lambda c: c.upper(),
                        help='set parity, one of {N E O S M}, default: N',
                        default='N')
    parser.add_argument('--stopbits',
                        choices=[1, 2],
                        type=int,
                        help='set stopbits, one of {1, 2}, default: 1',
                        default=1)
    args = parser.parse_args()
    print('Device name: {}'.format(args.device))
    mode = os.stat(args.device).st_mode
    if not S_ISCHR(mode):
        raise SystemExit('Expected a character device file')
    with serial.Serial(args.device,
                       baudrate=args.baudrate,
                       bytesize=args.bytesize,
                       parity=args.parity,
                       stopbits=args.stopbits,
                       timeout=1) as f_dev:
        attempts = 30
        print('Attempting to parse {} sentences:'.format(attempts))
        bad_msg_count = 0
        for _ in range(attempts):
            try:
                str_from_serial = f_dev.readline().decode('UTF-8')
            except UnicodeDecodeError:
                print(' Bad sentence: couldn\'t decode line')
                bad_msg_count += 1
                continue
            try:
                msg = pynmea2.parse(str_from_serial, check=True)
            except pynmea2.ChecksumError:
                print(' Bad sentence: checksum error')
                bad_msg_count += 1
                continue
            except pynmea2.ParseError:
                print(' Bad sentence: parse error')
                bad_msg_count += 1
                continue
            print(' Got sentence type: {}'.format(msg.sentence_type))
        print('Total bad sentences: {}'.format(bad_msg_count))
        if bad_msg_count > 3:
            raise SystemExit('Too many bad NMEA sentences')
        else:
            print('Acceptable number of bad NMEA sentences')
示例#6
0
 def is_char_device(self):
     """
     Whether this path is a character device.
     """
     try:
         return S_ISCHR(self.stat().st_mode)
     except OSError as e:
         if e.errno not in (ENOENT, ENOTDIR):
             raise
         return False
示例#7
0
文件: cli.py 项目: metatoaster/calmjs
def _check_interactive(*descriptors):
    for desc in descriptors:
        try:
            if not S_ISCHR(fstat(desc.fileno()).st_mode):
                return False
        except Exception:
            # Anything broken we are going to pretend this is not
            # interactive
            return False

    return True  # pragma: no cover
示例#8
0
文件: view.py 项目: numirias/nvfm
def filetype_str(mode):
    if S_ISCHR(mode):
        msg = 'character special device file'
    elif S_ISBLK(mode):
        msg = 'block special device file'
    elif S_ISFIFO(mode):
        msg = 'FIFO (named pipe)'
    elif S_ISSOCK(mode):
        msg = 'socket'
    else:
        msg = 'unknown file type'
    return msg
示例#9
0
 def is_char_device(self):
     """
     Whether this path is a character device.
     """
     try:
         return S_ISCHR(self.stat().st_mode)
     except OSError as e:
         if not _ignore_error(e):
             raise
         # Path doesn't exist or is a broken symlink
         # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
         return False
示例#10
0
 def is_char_device(self):
     """
     Whether this path is a character device.
     """
     try:
         return S_ISCHR(self.stat().st_mode)
     except OSError as e:
         #            if e.errno not in (ENOENT, ENOTDIR):
         if e_errno_not_in_ENOENT_ENOTDIR(e):  ###
             raise
         # Path doesn't exist or is a broken symlink
         # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
         return False
示例#11
0
 def is_char_device(self):
     """
     Whether this path is a character device.
     """
     try:
         return S_ISCHR(self.stat().st_mode)
     except OSError as e:
         if e.errno not in _IGNORED_ERROS:
             raise
         # Path doesn't exist or is a broken symlink
         # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
         return False
     except ValueError:
         # Non-encodable path
         return False
示例#12
0
 def is_char_device(self):
     """
     Whether this path is a character device.
     """
     try:
         return S_ISCHR(self.stat().st_mode)
     except OSError as e:
         if not _ignore_error(e):
             raise
         # Path doesn't exist or is a broken symlink
         # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
         return False
     except ValueError:
         # Non-encodable path
         return False
示例#13
0
    async def __new__(cls, loop, pipe, protocol, extra=None):
        fileno = pipe.fileno()
        mode = os.fstat(fileno).st_mode
        is_char = S_ISCHR(mode)
        is_fifo = S_ISFIFO(mode)
        is_socket = S_ISSOCK(mode)
        if not (is_char or is_fifo or is_socket):
            raise ValueError(
                'Pipe transport is only for pipes, sockets and character devices.'
            )

        if extra is None:
            extra = {}

        extra['pipe'] = pipe

        self = object.__new__(cls)
        self._extra = extra
        self.loop = loop
        self.protocol_paused = False
        self.pipe = pipe
        self.fileno = fileno
        self.protocol = protocol
        self._buffer = bytearray()
        self._connection_lost = 0
        self.closing = False  # Set when close() or write_eof() called.

        self._high_water = 65536
        self._low_water = 16384

        try:
            os.set_blocking(fileno, False)
            # skip 1 callback loop
            future = Future(loop)
            loop.call_soon(Future.set_result_if_pending, future, None)
            await future

            protocol.connection_made(self)

            # On AIX, the reader trick (to be notified when the read end of the  socket is closed) only works for
            # sockets. On other platforms it works for pipes and sockets.
            if is_socket or (is_fifo and not IS_AIX):
                loop.add_reader(fileno, self._read_ready)
        except:
            self.close()
            raise

        return self
示例#14
0
文件: color.py 项目: numirias/nvfm
 def file_hl_group(self, file, stat_res=None, stat_error=None):
     """Return the highlight group that `file` should be colored in."""
     if stat_error is not None:
         return 'Error'
     if stat_res is None:
         return self.file_hl_group(file, *stat_path(file))
     mode = stat_res.st_mode
     if not S_ISREG(mode):  # Not a regular file
         if S_ISLNK(mode):
             if self._colors_special.get('ln') == 'target':
                 # TODO
                 # resolved = file.resolve()
                 # if resolved == file:
                 #     # Don't try to resolve another time
                 #     # TODO
                 #     raise Exception('recursion! %s' % resolved)
                 return self.file_hl_group(file,
                                           *stat_path(file, lstat=False))
             else:
                 ansi_color = self._colors_special.get('ln')
         elif S_ISCHR(mode):
             ansi_color = self._colors_special.get('cd')
         elif S_ISDIR(mode):
             ansi_color = self._colors_special.get('di')
         elif S_ISFIFO(mode):
             ansi_color = self._colors_special.get('pi')
         elif S_ISBLK(mode):
             ansi_color = self._colors_special.get('bd')
         elif S_ISSOCK(mode):
             ansi_color = self._colors_special.get('so')
         else:
             # TODO Does this happen?
             return 'Error'
     elif mode & S_IXUSR:  # Executable
         ansi_color = self._colors_special.get('ex')
     else: # Regular file
         needle = file.name.lower()
         for pattern, colorcode in self._colors.items():
             if needle.endswith(pattern):
                 ansi_color = colorcode
                 break
         else:
             # TODO Could not find a target color
             return None
     if ansi_color is None:
         return None
     hl_group = 'color' + ansi_color.replace(';', '_')
     return hl_group
示例#15
0
 async def is_char_device(self) -> bool:
   """
   Whether this path is a character device.
   """
   try:
     stat = await self.stat()
     return S_ISCHR(stat.st_mode)
   except OSError as e:
     if not _ignore_error(e):
       raise
     # Path doesn't exist or is a broken symlink
     # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
     return False
   except ValueError:
     # Non-encodable path
     return False
示例#16
0
def check_input_files(file_path, force):
    """Check the status of the file.

    If the file is empty or doesn't exist AND if the file is NOT a
    fifo/block/named pipe then a warning is printed and sys.exit(1) is
    called
    """
    mode = None

    if file_path == '-':
        return

    try:
        mode = os.stat(file_path).st_mode
    except OSError:
        print("ERROR: Input file %s does not exist" % file_path,
              file=sys.stderr)

        if not force:
            print("NOTE: This can be overridden using the --force argument",
                  file=sys.stderr)
            print("Exiting", file=sys.stderr)
            sys.exit(1)
        else:
            return

    # block devices/stdin will be nonzero
    if S_ISBLK(mode) or S_ISFIFO(mode) or S_ISCHR(mode):
        return

    if not os.path.exists(file_path):
        print("ERROR: Input file %s does not exist; exiting" % file_path,
              file=sys.stderr)
        if not force:
            print("NOTE: This can be overridden using the --force argument",
                  file=sys.stderr)
            sys.exit(1)
    else:
        if os.stat(file_path).st_size == 0:
            print("ERROR: Input file %s is empty; exiting." % file_path,
                  file=sys.stderr)
            if not force:
                print(
                    "NOTE: This can be overridden using the --force"
                    " argument",
                    file=sys.stderr)
                sys.exit(1)
示例#17
0
def connect(device=DEFAULT_DEVICE):
    device = os.getenv("BLEMU_DEVICE", device)
    if not os.path.exists(device):
        raise ValueError("Device `%s` does not exist. Cannot connect" % device)

    mode = os.stat(device).st_mode
    ser = None
    if S_ISCHR(mode):
        ser = serial.Serial(port=device, baudrate=BAUD_RATE)
    elif S_ISFIFO(mode) or S_ISREG(mode):
        ser = open(device, "w")

    # So! Apparently when you connect to the arduino serial port, the
    # bootloader kicks in, resets the arduino and waits a second for a new
    # program to be loaded before running the actual already stored code
    time.sleep(2)
    return ser
示例#18
0
def analyze(src, length=io.DEFAULT_BUFFER_SIZE):
    md5 = hashlib.md5()
    src = os.path.abspath(src)
    try:
        mode = os.stat(src).st_mode

        if S_ISREG(mode):
            upsert_file_metadata(src,
                                 stat_types['REGULAR'],
                                 size=os.path.getsize(src),
                                 extension=os.path.splitext(src)[1])
        elif S_ISDIR(mode):
            upsert_file_metadata(src, stat_types['DIRECTORY'])
        elif S_ISCHR(mode):
            upsert_file_metadata(src, stat_types['CHAR'])
        elif S_ISBLK(mode):
            upsert_file_metadata(src, stat_types['BLOCK'])
        elif S_ISFIFO(mode):
            upsert_file_metadata(src, stat_types['FIFO'])
        elif S_ISLNK(mode):
            upsert_file_metadata(src, stat_types['SYMLINK'])
        elif S_ISSOCK(mode):
            upsert_file_metadata(src, stat_types['SOCKET'])
        else:
            upsert_file_metadata(src, stat_types['UNKNOWN'])
    except FileNotFoundError:
        mode = os.stat(src, follow_symlinks=False).st_mode
        if S_ISLNK(mode):
            upsert_file_metadata(src, stat_types['BROKEN_SYMLINK'])

    # Just return the MD5 hash of an empty string for non-regular files
    if not S_ISREG(mode):
        return md5

    try:
        upsert_file_metadata(src,
                             mime_type=(magic.from_file(src, mime=True)),
                             mime_detail=magic.from_file(src))
        with io.open(src, mode="rb") as fd:
            for chunk in iter(lambda: fd.read(length), b''):
                md5.update(chunk)
    except OSError:
        upsert_file_metadata(src, stat_types['ERROR'])
        pass
    return md5
示例#19
0
 def get_file_type(self, root, filename):
     filepath = fpath.join(root, filename)
     filemode = stat(filepath).st_mode
     if S_ISREG(filemode):
         return "f"
     elif S_ISSOCK(filemode):
         return "s"
     elif S_ISFIFO(filemode):
         return "p"
     elif S_ISLNK(filemode):
         return "l"
     elif S_ISDIR(filemode):
         return "d"
     elif S_ISCHR(filemode):
         return "c"
     elif S_ISBLK(filemode):
         return "b"
     return "?"
示例#20
0
def get_ftype_and_perm(mode):
    """ Returns a tuple of whether the file is: file(regular file)/dir/slink
    /char. spec/block spec/pipe/socket and the permission bits of the file.
    If it does not match any of the cases below (it will return "unknown" twice)"""
    if S_ISREG(mode):
        return "file", S_IMODE(mode)
    if S_ISDIR(mode):
        return "dir", S_IMODE(mode)
    if S_ISLNK(mode):
        return "slink", S_IMODE(mode)
    if S_ISCHR(mode):
        return "character special", S_IMODE(mode)
    if S_ISBLK(mode):
        return "block special", S_IMODE(mode)
    if S_ISFIFO(mode):
        return "pipe", S_IMODE(mode)
    if S_ISSOCK(mode):
        return "socket", S_IMODE(mode)
    return "unknown", "unknown"
示例#21
0
def _is_gpiochip_cdev(path: str) -> bool:
    try:
        statbuf = lstat(path)
    except FileNotFoundError:
        return False

    # Is it a character device?
    if not S_ISCHR(statbuf.st_mode):
        # Passing a file descriptor not associated with a character
        # device to ioctl() makes it set errno to ENOTTY. Let's do
        # the same in order to stay compatible with the versions of
        # libgpiod from before the introduction of this routine.
        set_errno(ENOTTY)
        return False

    # Do we have a corresponding sysfs attribute?
    name = basename(path)
    sysfsp = "/sys/bus/gpio/devices/{}/dev".format(name)
    if not access(sysfsp, R_OK):
        # This is a character device but not the one we're after.
        # Before the introduction of this function, we'd fail with
        # ENOTTY on the first GPIO ioctl() call for this file
        # descriptor. Let's stay compatible here and keep returning
        # the same error code.
        set_errno(ENOTTY)
        return False

    # Make sure the major and minor numbers of the character device
    # correspond to the ones in the dev attribute in sysfs.
    devstr = "{}:{}".format(major(statbuf.st_rdev), minor(statbuf.st_rdev))

    try:
        with open(sysfsp, "r") as fd:
            sysfsdev = fd.read(len(devstr))
    except FileNotFoundError:
        return False

    if sysfsdev != devstr:
        set_errno(ENODEV)
        return False

    return True
示例#22
0
def get_ctl(path, mode):
    """get the string to control device access for cgroup
    :param path: the device file path
    :param mode: either "r" or "rw"
    :return: the string to control device access
    """
    try:
        st = os.stat(path)
    except OSError as e:
        log.error("Failed to get stat of {}: {}".format(path, str(e)))
        raise

    t = ""
    if S_ISBLK(st.st_mode):
        t = "b"
    elif S_ISCHR(st.st_mode):
        t = "c"
    if t and mode in ("r", "rw"):
        return "{} {}:{} {}".format(t, os.major(st.st_rdev),
                                    os.minor(st.st_rdev), mode)
    raise RuntimeError("Failed to get control string of {}".format(path))
示例#23
0
文件: wdi3.py 项目: danfe/scripts
def check_WDC_drive(dev):
    print('Checking if %s is a Western Digital drive...' % dev, end='')

    from os import getuid, path, stat
    from stat import S_ISCHR

    # Perform some extra sanity checks first...
    if not path.exists('/dev/%s' % dev):
        print(' nonexistent device')
        return False
    if not S_ISCHR(stat('/dev/%s' % dev).st_mode):
        print(' not a character device')
        return False

    p = run([
        'camcontrol', 'cmd', dev, '-v', '-a',
        'EC 00 00 00 00 00 00 00 00 00 01 00', '-i', '512', '-'
    ],
            capture_output=True)
    if p.returncode != 0:
        print(' failed')
        # Hint: camcontrol(8) requires root to access /dev/xpt0
        if getuid() != 0: print('Are you running %s as root?' % sys.argv[0])
        return False

    # XXX: should probably check for "FX", "NEC", "Pioneer", or "SHARP"
    # because they don't require byteswap, but I haven't seen those in
    # usage for quite a while, so let's just waive the check for now :)

    model = struct.pack('<20H', *struct.unpack_from('>20H', p.stdout, 54))
    if model[:3] == b'WDC':
        print(' apparently so!')
        return True

    print(' no :(')
    print('The drive says its model is %s' % model.strip().decode())

    if not force: return False
    verbose_print('Proceeding anyway because --force option was given')
    return True
示例#24
0
    async def __new__(cls, loop, pipe, protocol, extra=None):
        fileno = pipe.fileno()
        mode = os.fstat(fileno).st_mode
        if not (S_ISFIFO(mode) or S_ISSOCK(mode) or S_ISCHR(mode)):
            raise ValueError(
                'Pipe transport is only for pipes, sockets and character devices.'
            )

        self = object.__new__(cls)
        if extra is None:
            extra = {}

        extra['pipe'] = pipe

        self._extra = extra
        self.loop = loop
        self.pipe = pipe
        self.fileno = fileno
        self.protocol = protocol
        self.closing = False
        self._paused = False

        try:
            os.set_blocking(fileno, False)
            # skip 1 callback loop
            future = Future(loop)
            loop.call_soon(Future.set_result_if_pending, future, None)
            await future

            protocol.connection_made(self)
            loop.add_reader(fileno, self._read_ready)

        except:
            self.close()
            raise

        return self
示例#25
0
def regfile(a):
    """Return if st_mode info in 'a' points to a file or file like filesystem
    object"""

    return S_ISREG(a) or S_ISFIFO(a) or S_ISSOCK(a) or S_ISCHR(a)
示例#26
0
 def is_device(self):
     mode = os.lstat(self._name).st_mode
     return S_ISCHR(mode) or S_ISBLK(mode)
示例#27
0
def is_terminal(fileno: int) -> bool:
    """ Returns true if the given file number belongs to a terminal (stdout)"""
    return S_ISCHR(os.fstat(fileno).st_mode)
示例#28
0
def stat_is_special(attr):
    return S_ISCHR(attr.st_mode) or S_ISBLK(attr.st_mode)
示例#29
0
 def isdev(self):
     from stat import S_ISBLK, S_ISCHR
     mode = self.__st_mode()
     return S_ISBLK(mode) or S_ISCHR(mode)
示例#30
0
 def ischardev(self):
     from stat import S_ISCHR
     return S_ISCHR(self.__st_mode())