Python os.lseek() Examples
The following are 30
code examples of os.lseek().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
os
, or try the search function
.
Example #1
Source File: test_fd.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_open(self): test_filename = "tmp.open.test" fd1 = os.open(test_filename + "1", flags) # make sure fd+1 and fd+2 are closed os.closerange(fd1 + 1, fd1 + 2) # open should return the lowest-numbered file descriptor not currently open # for the process fd2 = os.open(test_filename + "2", flags) fd3 = os.open(test_filename + "3", flags) os.close(fd2) self.assertRaisesMessage(OSError, "[Errno 9] Bad file descriptor", os.lseek, fd2, os.SEEK_SET, 0) fd4 = os.open(test_filename + "4", flags) self.assertEqual(fd4, fd2) os.close(fd1) os.close(fd3) os.close(fd4) for i in range(1, 5): os.unlink(test_filename + str(i))
Example #2
Source File: gpio.py From python-periphery with MIT License | 6 votes |
def write(self, value): if not isinstance(value, bool): raise TypeError("Invalid value type, should be bool.") # Write value try: if value: os.write(self._fd, b"1\n") else: os.write(self._fd, b"0\n") except OSError as e: raise GPIOError(e.errno, "Writing GPIO: " + e.strerror) # Rewind try: os.lseek(self._fd, 0, os.SEEK_SET) except OSError as e: raise GPIOError(e.errno, "Rewinding GPIO: " + e.strerror)
Example #3
Source File: gpio.py From python-periphery with MIT License | 6 votes |
def read(self): # Read value try: buf = os.read(self._fd, 2) except OSError as e: raise GPIOError(e.errno, "Reading GPIO: " + e.strerror) # Rewind try: os.lseek(self._fd, 0, os.SEEK_SET) except OSError as e: raise GPIOError(e.errno, "Rewinding GPIO: " + e.strerror) if buf[0] == b"0"[0]: return False elif buf[0] == b"1"[0]: return True raise GPIOError(None, "Unknown GPIO value: {}".format(buf))
Example #4
Source File: test_posix.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
def test_fs_holes(self): # Even if the filesystem doesn't report holes, # if the OS supports it the SEEK_* constants # will be defined and will have a consistent # behaviour: # os.SEEK_DATA = current position # os.SEEK_HOLE = end of file position with open(support.TESTFN, 'r+b') as fp: fp.write(b"hello") fp.flush() size = fp.tell() fno = fp.fileno() try : for i in range(size): self.assertEqual(i, os.lseek(fno, i, os.SEEK_DATA)) self.assertLessEqual(size, os.lseek(fno, i, os.SEEK_HOLE)) self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_DATA) self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_HOLE) except OSError : # Some OSs claim to support SEEK_HOLE/SEEK_DATA # but it is not true. # For instance: # http://lists.freebsd.org/pipermail/freebsd-amd64/2012-January/014332.html raise unittest.SkipTest("OSError raised!")
Example #5
Source File: common.py From deplicate with MIT License | 6 votes |
def _chunksum(fd, read, size, bufsizes, whence): buf0, buf1 = bufsizes offset, how = whence x = _xxhash_xxh() update = x.update if offset: os.lseek(fd, offset, how) left = size data = read(buf0) while left and data: update(data) left -= buf0 data = read(buf0) if buf1: data = read(buf1) update(data) return x.hexdigest()
Example #6
Source File: virtio_console_guest.py From avocado-vt with GNU General Public License v2.0 | 6 votes |
def lseek(self, port, pos, how): """ Use lseek on the device. The device is unseekable so PASS is returned when lseek command fails and vice versa. :param port: Name of the port :param pos: Offset :param how: Relative offset os.SEEK_{SET,CUR,END} """ fd = self._open([port])[0] try: os.lseek(fd, pos, how) except Exception as inst: if inst.errno == 29: print("PASS: the lseek failed as expected") else: print(inst) print("FAIL: unknown error") else: print("FAIL: the lseek unexpectedly passed")
Example #7
Source File: test_posix.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
def test_writev(self): fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT) try: n = os.writev(fd, (b'test1', b'tt2', b't3')) self.assertEqual(n, 10) os.lseek(fd, 0, os.SEEK_SET) self.assertEqual(b'test1tt2t3', posix.read(fd, 10)) # Issue #20113: empty list of buffers should not crash try: size = posix.writev(fd, []) except OSError: # writev(fd, []) raises OSError(22, "Invalid argument") # on OpenIndiana pass else: self.assertEqual(size, 0) finally: os.close(fd)
Example #8
Source File: led.py From python-periphery with MIT License | 6 votes |
def read(self): """Read the brightness of the LED. Returns: int: Current brightness. Raises: LEDError: if an I/O or OS error occurs. """ # Read value try: buf = os.read(self._fd, 8) except OSError as e: raise LEDError(e.errno, "Reading LED brightness: " + e.strerror) # Rewind try: os.lseek(self._fd, 0, os.SEEK_SET) except OSError as e: raise LEDError(e.errno, "Rewinding LED brightness: " + e.strerror) return int(buf)
Example #9
Source File: storage_file.py From qubes-core-admin with GNU Lesser General Public License v2.1 | 6 votes |
def _get_loop_size(self, path): sudo = [] if os.getuid() == 0 else ['sudo'] try: loop_name = subprocess.check_output( sudo + ['losetup', '--associated', path]).decode().split(':')[0] if os.getuid() != 0: return int( subprocess.check_output( ['sudo', 'blockdev', '--getsize64', loop_name])) fd = os.open(loop_name, os.O_RDONLY) try: return os.lseek(fd, 0, os.SEEK_END) finally: os.close(fd) except subprocess.CalledProcessError: return None
Example #10
Source File: PythonIoTasks.py From ufora with Apache License 2.0 | 6 votes |
def loadFileSliceDataset(datasetDescriptor, vdid, vdm): fd = None path = datasetDescriptor.asFileSliceDataset.file.path lowIndex = datasetDescriptor.asFileSliceDataset.lowOffset highIndex = datasetDescriptor.asFileSliceDataset.highOffset try: fd = os.open(path, os.O_RDONLY) os.lseek(fd, lowIndex, os.SEEK_SET) if not vdm.loadByteArrayIntoExternalDatasetPageFromFileDescriptor( vdid, fd, highIndex - lowIndex): raise DatasetLoadException("Coulnd't load file slice into VDM") except os.error as e: message = 'Error loading file slice dataset: %s, %d-%d:\n%s' % ( path, lowIndex, highIndex, e) logging.error(message) raise DatasetLoadException(message) finally: if fd is not None: os.close(fd)
Example #11
Source File: environment.py From miasm with GNU General Public License v2.0 | 5 votes |
def lseek(self, offset, whence): return os.lseek(self.real_fd, offset, whence) # SEEK_SET
Example #12
Source File: test_subprocess.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_stdout_filedes(self): # stdout is set to open file descriptor tf = tempfile.TemporaryFile() self.addCleanup(tf.close) d = tf.fileno() p = subprocess.Popen([sys.executable, "-c", 'import sys; sys.stdout.write("orange")'], stdout=d) p.wait() os.lseek(d, 0, 0) self.assertEqual(os.read(d, 1024), b"orange")
Example #13
Source File: unix_events.py From Imogen with MIT License | 5 votes |
def _sock_sendfile_update_filepos(self, fileno, offset, total_sent): if total_sent > 0: os.lseek(fileno, offset, os.SEEK_SET)
Example #14
Source File: _pyio.py From Imogen with MIT License | 5 votes |
def readall(self): """Read all data from the file, returned as bytes. In non-blocking mode, returns as much as is immediately available, or None if no data is available. Return an empty bytes object at EOF. """ self._checkClosed() self._checkReadable() bufsize = DEFAULT_BUFFER_SIZE try: pos = os.lseek(self._fd, 0, SEEK_CUR) end = os.fstat(self._fd).st_size if end >= pos: bufsize = end - pos + 1 except OSError: pass result = bytearray() while True: if len(result) >= bufsize: bufsize = len(result) bufsize += max(bufsize, DEFAULT_BUFFER_SIZE) n = bufsize - len(result) try: chunk = os.read(self._fd, n) except BlockingIOError: if result: break return None if not chunk: # reached the end of the file break result += chunk return bytes(result)
Example #15
Source File: _pyio.py From Imogen with MIT License | 5 votes |
def seek(self, pos, whence=SEEK_SET): """Move to new file position. Argument offset is a byte count. Optional argument whence defaults to SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values are SEEK_CUR or 1 (move relative to current position, positive or negative), and SEEK_END or 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). Note that not all file objects are seekable. """ if isinstance(pos, float): raise TypeError('an integer is required') self._checkClosed() return os.lseek(self._fd, pos, whence)
Example #16
Source File: test_posix.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_lockf(self): fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT) try: os.write(fd, b'test') os.lseek(fd, 0, os.SEEK_SET) posix.lockf(fd, posix.F_LOCK, 4) # section is locked posix.lockf(fd, posix.F_ULOCK, 4) finally: os.close(fd)
Example #17
Source File: _pyio.py From Imogen with MIT License | 5 votes |
def tell(self): """tell() -> int. Current file position. Can raise OSError for non seekable files.""" self._checkClosed() return os.lseek(self._fd, 0, SEEK_CUR)
Example #18
Source File: environment.py From miasm with GNU General Public License v2.0 | 5 votes |
def seek(self, offset): return self.lseek(offset, 0) # SEEK_SET
Example #19
Source File: test_os.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_lseek(self): self.check(os.lseek, 0, 0)
Example #20
Source File: test_subprocess.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_stderr_filedes(self): # stderr is set to open file descriptor tf = tempfile.TemporaryFile() self.addCleanup(tf.close) d = tf.fileno() p = subprocess.Popen([sys.executable, "-c", 'import sys; sys.stderr.write("strawberry")'], stderr=d) p.wait() os.lseek(d, 0, 0) self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Example #21
Source File: passthrough.py From gitfs with Apache License 2.0 | 5 votes |
def read(self, path, length, offset, fh): os.lseek(fh, offset, os.SEEK_SET) return os.read(fh, length)
Example #22
Source File: test_subprocess.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_stdin_filedes(self): # stdin is set to open file descriptor tf = tempfile.TemporaryFile() self.addCleanup(tf.close) d = tf.fileno() os.write(d, b"pear") os.lseek(d, 0, 0) p = subprocess.Popen([sys.executable, "-c", 'import sys; sys.exit(sys.stdin.read() == "pear")'], stdin=d) p.wait() self.assertEqual(p.returncode, 1)
Example #23
Source File: test_largefile.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_lseek(self): with self.open(TESTFN, 'rb') as f: self.assertEqual(os.lseek(f.fileno(), 0, 0), 0) self.assertEqual(os.lseek(f.fileno(), 42, 0), 42) self.assertEqual(os.lseek(f.fileno(), 42, 1), 84) self.assertEqual(os.lseek(f.fileno(), 0, 1), 84) self.assertEqual(os.lseek(f.fileno(), 0, 2), size+1+0) self.assertEqual(os.lseek(f.fileno(), -10, 2), size+1-10) self.assertEqual(os.lseek(f.fileno(), -size-1, 2), 0) self.assertEqual(os.lseek(f.fileno(), size, 0), size) # the 'a' that was written at the end of file above self.assertEqual(f.read(1), b'a')
Example #24
Source File: test_socket.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def checkFDs(self, fds): # Check that the file descriptors in the given list contain # their correct list indices as ASCII numbers. for n, fd in enumerate(fds): os.lseek(fd, 0, os.SEEK_SET) self.assertEqual(os.read(fd, 1024), str(n).encode())
Example #25
Source File: _pyio.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def tell(self): """tell() -> int. Current file position. Can raise OSError for non seekable files.""" self._checkClosed() return os.lseek(self._fd, 0, SEEK_CUR)
Example #26
Source File: _pyio.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def seek(self, pos, whence=SEEK_SET): """Move to new file position. Argument offset is a byte count. Optional argument whence defaults to SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values are SEEK_CUR or 1 (move relative to current position, positive or negative), and SEEK_END or 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). Note that not all file objects are seekable. """ if isinstance(pos, float): raise TypeError('an integer is required') self._checkClosed() return os.lseek(self._fd, pos, whence)
Example #27
Source File: _pyio.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def readall(self): """Read all data from the file, returned as bytes. In non-blocking mode, returns as much as is immediately available, or None if no data is available. Return an empty bytes object at EOF. """ self._checkClosed() self._checkReadable() bufsize = DEFAULT_BUFFER_SIZE try: pos = os.lseek(self._fd, 0, SEEK_CUR) end = os.fstat(self._fd).st_size if end >= pos: bufsize = end - pos + 1 except OSError: pass result = bytearray() while True: if len(result) >= bufsize: bufsize = len(result) bufsize += max(bufsize, DEFAULT_BUFFER_SIZE) n = bufsize - len(result) try: chunk = os.read(self._fd, n) except BlockingIOError: if result: break return None if not chunk: # reached the end of the file break result += chunk return bytes(result)
Example #28
Source File: base.py From gitfs with Apache License 2.0 | 5 votes |
def clear(self): """Discards any logs produced so far.""" # seek to the end of the file, since we want to discard old messages os.lseek(self.file_descriptor, 0, os.SEEK_END) self._partial_line = None self.line_buffer = collections.deque()
Example #29
Source File: passthrough.py From gitfs with Apache License 2.0 | 5 votes |
def write(self, path, buf, offset, fh): os.lseek(fh, offset, os.SEEK_SET) return os.write(fh, buf)
Example #30
Source File: unix.py From learn_python3_spider with MIT License | 5 votes |
def readChunk(self, offset, length): return self.server.avatar._runAsUser( [(os.lseek, (self.fd, offset, 0)), (os.read, (self.fd, length))])