Python os.truncate() Examples

The following are 13 code examples of os.truncate(). 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: oxfs.py    From oxfs with MIT License 6 votes vote down vote up
def truncate(self, path, length, fh=None):
        realpath = self.remotepath(path)
        cachefile = self.cachefile(realpath)
        if not os.path.exists(cachefile):
            if self.empty_file(realpath):
                self.create(path, 'wb')
            else:
                raise FuseOSError(ENOENT)

        status = os.truncate(cachefile, length)
        self.logger.info(self.extract(os.lstat(cachefile)))
        self.attributes.insert(realpath, self.extract(os.lstat(cachefile)))
        task = Task(xxhash.xxh64(realpath).intdigest(),
                    self._truncate, realpath, length)
        self.taskpool.submit(task)
        return status 
Example #2
Source File: mkosi.py    From mkosi with GNU Lesser General Public License v2.1 6 votes vote down vote up
def create_image(args: CommandLineArguments, root: str, for_cache: bool) -> Optional[BinaryIO]:
    if not args.output_format.is_disk():
        return None

    with complete_step('Creating partition table',
                       'Created partition table as {.name}') as output:

        f: BinaryIO = cast(BinaryIO, tempfile.NamedTemporaryFile(prefix='.mkosi-', delete=not for_cache,
                                                                 dir=os.path.dirname(args.output)))
        output.append(f)
        disable_cow(f.name)
        f.truncate(image_size(args))

        table, run_sfdisk = determine_partition_table(args)

        if run_sfdisk:
            run(["sfdisk", "--color=never", f.name], input=table.encode("utf-8"), check=True)
            run(["sync"])

        args.ran_sfdisk = run_sfdisk

    return f 
Example #3
Source File: mkosi.py    From mkosi with GNU Lesser General Public License v2.1 6 votes vote down vote up
def make_minimal_ext4(args: CommandLineArguments, root: str, for_cache: bool) -> Optional[BinaryIO]:
    if args.output_format != OutputFormat.gpt_ext4:
        return None
    if not args.minimize:
        return None
    if for_cache:
        return None

    with complete_step('Creating ext4 root file system'):
        f: BinaryIO = cast(BinaryIO, tempfile.NamedTemporaryFile(prefix=".mkosi-mkfs-ext4",
                                                                 dir=os.path.dirname(args.output)))
        f.truncate(args.root_size)
        run(["mkfs.ext4", "-I", "256", "-L", "root", "-M", "/", "-d", root, f.name], check=True)

    with complete_step('Minimizing ext4 root file system'):
        run(["resize2fs", "-M", f.name])

    return f 
Example #4
Source File: mkosi.py    From mkosi with GNU Lesser General Public License v2.1 6 votes vote down vote up
def make_minimal_btrfs(args: CommandLineArguments, root: str, for_cache: bool) -> Optional[BinaryIO]:
    if args.output_format != OutputFormat.gpt_btrfs:
        return None
    if not args.minimize:
        return None
    if for_cache:
        return None

    with complete_step('Creating minimal btrfs root file system'):
        f: BinaryIO = cast(BinaryIO, tempfile.NamedTemporaryFile(prefix=".mkosi-mkfs-btrfs",
                                                                 dir=os.path.dirname(args.output)))
        f.truncate(args.root_size)

        command = ["mkfs.btrfs", "-L", "root", "-d", "single", "-m", "single", "--shrink", "--rootdir", root, f.name]
        try:
            run(command, check=True)
        except subprocess.CalledProcessError as e:
            # The --shrink option was added in btrfs-tools 4.14.1, before that it was the default behaviour.
            # If the above fails, let's see if things work if we drop it
            command.remove("--shrink")
            run(command, check=True)

    return f 
Example #5
Source File: oxfs.py    From oxfs with MIT License 5 votes vote down vote up
def _truncate(self, thread_local_data, path, length):
        self.logger.info('sftp truncate {}'.format(path))
        sftp = self.current_thread_sftp(thread_local_data)
        return sftp.truncate(path, length) 
Example #6
Source File: test_os.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_ftruncate(self):
        self.check(os.truncate, 0)
        self.check(os.ftruncate, 0) 
Example #7
Source File: test_os.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_ftruncate(self):
        self.check(os.truncate, 0)
        self.check(os.ftruncate, 0) 
Example #8
Source File: image_installer.py    From intel-iot-refkit with MIT License 5 votes vote down vote up
def create_internal_disk(self):
        """Create a internal-image*.wic in the resultdir that runqemu can use."""
        copyfile(os.path.join(self.image_dir, 'refkit-installer-image-%s.qemuboot.conf' % self.image_arch),
                 os.path.join(self.resultdir, 'internal-image-%s.qemuboot.conf' % self.image_arch))
        for ovmf in glob('%s/ovmf*' % self.image_dir):
            os.symlink(ovmf, os.path.join(self.resultdir, os.path.basename(ovmf)))
        with open(os.path.join(self.resultdir, 'internal-image-%s.wic' % self.image_arch), 'w') as f:
            # empty, sparse file of 8GB
            os.truncate(f.fileno(), 8 * 1024 * 1024 * 1024) 
Example #9
Source File: googlesheets.py    From cjworkbench with GNU Affero General Public License v3.0 5 votes vote down vote up
def TODO_i18n_fetch_error(output_path: Path, message: str):
    os.truncate(output_path, 0)
    return [I18nMessage("TODO_i18n", {"text": message}, None)] 
Example #10
Source File: test_os.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_ftruncate(self):
        self.check(os.truncate, 0)
        self.check(os.ftruncate, 0) 
Example #11
Source File: mitogen-fuse.py    From mitogen with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _truncate(path, length):
    fd = os.open(path, os.O_RDWR)
    try:
        os.truncate(fd, length)
    finally:
        os.close(fd) 
Example #12
Source File: mitogen-fuse.py    From mitogen with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def truncate(self, path, length, fh=None):
        path = path.decode(self.encoding)
        _evil_name(path)
        return errno_call(self._context, _truncate, path, length) 
Example #13
Source File: googlesheets.py    From cjworkbench with GNU Affero General Public License v3.0 4 votes vote down vote up
def do_download(
    sheet_id: str, sheet_mime_type: str, oauth2_client: oauth2.Client, output_path: Path
) -> List[I18nMessage]:
    """
    Download spreadsheet from Google.

    If `sheet_mime_type` is 'application/vnd.google-apps.spreadsheet', use
    GDrive API to _export_ a text/csv. Otherwise, use GDrive API to _download_
    the file.
    """
    if sheet_mime_type == "application/vnd.google-apps.spreadsheet":
        url = _generate_google_sheet_url(sheet_id)
        sheet_mime_type = "text/csv"
    else:
        url = _generate_gdrive_file_url(sheet_id)
        # and use the passed sheet_mime_type

    url, headers, _ = oauth2_client.add_token(url, headers={})

    try:
        await httpfile.download(url, output_path, headers=headers, ssl=SSL_CONTEXT)
    except HttpError.NotSuccess as err:
        response = err.response
        if response.status_code == 401:
            return TODO_i18n_fetch_error(
                output_path, "Invalid credentials. Please reconnect to Google Drive."
            )
        elif response.status_code == 403:
            return TODO_i18n_fetch_error(
                output_path,
                "You chose a file your logged-in user cannot access. Please reconnect to Google Drive or choose a different file.",
            )
        elif response.status_code == 404:
            return TODO_i18n_fetch_error(
                output_path, "File not found. Please choose a different file."
            )
        else:
            return [err.i18n_message]
    except HttpError as err:
        # HACK: *err.i18n_message because i18n_message is a tuple
        # compatible with I18nMessage() ctor
        os.truncate(output_path, 0)
        return [err.i18n_message]

    return []