Todos os produtos
Search
Central de documentação

Object Storage Service:Acesso somente leitura do tipo arquivo com o OSS SDK for Python 2.0

Última atualização: Jul 03, 2026

Acesse objetos do OSS como objetos de arquivo Python somente leitura usando a interface File-Like no OSS SDK for Python 2.0.

Observações de uso

Método

O OSS SDK for Python 2.0 fornece a interface File-Like para acesso somente leitura a objetos de bucket por meio da classe ReadOnlyFile.

  • A classe ReadOnlyFile suporta os modos de fluxo único e prefetch. Ajuste o número de tarefas paralelas para melhorar a velocidade de leitura.

  • A reconexão integrada lida com quedas de conexão em redes instáveis.

class ReadOnlyFile:
    ...

def open_file(self, bucket: str, key: str, version_id: Optional[str] = None, request_payer: Optional[str] = None, **kwargs) -> ReadOnlyFile:
    ...

Parâmetros da solicitação

Parâmetro

Tipo

Descrição

bucket

str

Nome do bucket.

key

str

Nome do objeto.

version_id

str

ID de versão do objeto. Válido apenas quando existem várias versões.

request_payer

str

Defina como requester quando o pagamento pelo solicitante estiver ativado.

**kwargs

Any

Argumentos de palavra-chave opcionais (dicionário).

Opções de kwargs

Opção

Tipo

Descrição

enable_prefetch

bool

Ativa o modo prefetch. Padrão: desativado.

prefetch_num

int

Número de blocos de prefetch. Padrão: 3. Efetivo apenas no modo prefetch.

chunk_size

int

Tamanho de cada bloco de prefetch em MiB. Padrão: 6. Efetivo apenas no modo prefetch.

prefetch_threshold

int

Limiar de leitura sequencial antes da ativação do prefetch, em MiB. Padrão: 20.

block_size

int

Tamanho de um bloco. Valor padrão: None.

Parâmetros de resposta

Parâmetro

Tipo

Descrição

file

ReadOnlyFile

Instância ReadOnlyFile.

Métodos comuns de ReadOnlyFile

Método

Descrição

close(self)

Fecha o arquivo e libera recursos, como memória e sockets ativos.

read(self, n=None)

Lê até n bytes do objeto e retorna os dados lidos.

seek(self, pos, whence=0)

Define a posição de leitura. Valores de whence: 0 (início), 1 (posição atual), 2 (fim).

Stat() (os.FileInfo, error)

Consulta informações do objeto, incluindo tamanho, hora da última modificação e metadados.

Importante

Se ocorrerem múltiplas leituras fora de ordem no modo prefetch, o SDK retornará ao modo de fluxo único.

Exemplos

Ler todo o objeto usando o modo de fluxo único

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser for parsing arguments from the command line.
parser = argparse.ArgumentParser(description="open file sample")

# (Required) Specify the region parameter, which specifies the region in which the bucket is located. 
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# (Required) Specify the --bucket parameter, which specifies the name of the bucket.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# (Optional) Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

# (Required) Specify the --key parameter, which specifies the name of the object.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    # Parse the command-line parameters.
    args = parser.parse_args()

    // Obtain access credentials (AccessKey ID and AccessKey secret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK.
    cfg = oss.config.load_default()

    # Specify the credential provider.
    cfg.credentials_provider = credentials_provider

    # Specify the region in which the bucket is located.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance.
    client = oss.Client(cfg)

    # Use the open_file method to open the object in the bucket.
    result = client.open_file(
        bucket=args.bucket,           # The name of the bucket.
        key=args.key,                # The name of the object.
    )

    # Display the object, read the data, and decode it to the string format.
    print(f'content: {result.read().decode()}')

    # Closes the object to release resources.
    result.close()

if __name__ == "__main__":
    main() # Specify the entry points in the main function of the script when the script is directly run.
    main()

Ler todo o objeto usando o modo prefetch

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser for parsing arguments from the command line.
parser = argparse.ArgumentParser(description="open file sample")

# (Required) Specify the region parameter, which specifies the region in which the bucket is located. 
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# (Required) Specify the --bucket parameter, which specifies the name of the bucket.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# (Optional) Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

# (Required) Specify the --key parameter, which specifies the name of the object.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    # Parse the command-line parameters.
    args = parser.parse_args()

    // Obtain access credentials (AccessKey ID and AccessKey secret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK.
    cfg = oss.config.load_default()

    # Specify the credential provider.
    cfg.credentials_provider = credentials_provider

    # Specify the region in which the bucket is located.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance.
    client = oss.Client(cfg)

    # Use the open_file method to open the object in the bucket.
    result = client.open_file(
        bucket=args.bucket,           # The name of the bucket.
        key=args.key,                # The name of the object.
        enable_prefetch=True,        # Specify whether to enable the prefetch mode. Default value: true.
   )

    # Display the object, read the data, and decode it to the string format.
    print(f'content: {result.read().decode()}')

    # Closes the object to release resources.
    result.close()

if __name__ == "__main__":
    main() # Specify the entry points in the main function of the script when the script is directly run.
    main()

Ler dados restantes de uma posição específica usando o método **Seek**

import argparse
import os
import io
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser for parsing arguments from the command line.
parser = argparse.ArgumentParser(description="open file sample")

# (Required) Specify the region parameter, which specifies the region in which the bucket is located. 
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# (Required) Specify the --bucket parameter, which specifies the name of the bucket.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# (Optional) Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

# (Required) Specify the --key parameter, which specifies the name of the object.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    # Parse the command-line parameters.
    args = parser.parse_args()

    // Obtain access credentials (AccessKey ID and AccessKey secret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK.
    cfg = oss.config.load_default()

    # Specify the credential provider.
    cfg.credentials_provider = credentials_provider

    # Specify the region in which the bucket is located.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance.
    client = oss.Client(cfg)

    // Initialize the oss.ReadOnlyFile object.
    rf: oss.ReadOnlyFile = None

    # Use the WITH statement to open the object and ensure that the resources are automatically closed after the object read operation is complete.
    with client.open_file(args.bucket, args.key) as f:
        rf = f # Assign the object to the rf variable.

        # Move the file pointer to the specified position. In this example, the file pointer is 1 byte offset to the beginning of the object.
        f.seek(1, os.SEEK_SET)

        # Read the content of the object into a byte stream (BytesIO) in memory.
        copied_stream = io.BytesIO(rf.read())

        # Display the length of the data written to the byte stream.
        print(f'written: {len(copied_stream.getvalue())}')

        # Display the read content. The byte stream is decoded to the string format.
        print(f'read: {copied_stream.getvalue()}')

if __name__ == "__main__":
    main() # Specify the entry points in the main function of the script when the script is directly run.
    main()

Referências

  • Referência completa do design da API: File-Like (GitHub).