Tous les produits
Search
Centre de documentation

Object Storage Service:Accès en lecture seule de type fichier avec OSS SDK for Python 2.0

Dernière mise à jour :Aug 08, 2026

Accédez aux objets OSS comme à des objets fichier Python en lecture seule grâce à l'interface File-Like d'OSS SDK for Python 2.0.

Remarques

Méthode

OSS SDK for Python 2.0 propose l'interface File-Like permettant un accès en lecture seule aux objets du bucket via la classe ReadOnlyFile.

  • ReadOnlyFile prend en charge les modes mono-flux et prélecture. Ajustez le nombre de tâches parallèles pour améliorer la vitesse de lecture.

  • La reconnexion intégrée gère les coupures de connexion sur les réseaux instables.

class ReadOnlyFile:
    ...

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

Paramètres de requête

Paramètre

Type

Description

bucket

str

Nom du bucket.

key

str

Nom de l'objet.

version_id

str

ID de version de l'objet. Valide uniquement si plusieurs versions existent.

request_payer

str

Définissez sur requester lorsque le paiement par demandeur est activé.

**kwargs

Any

Arguments optionnels sous forme de mots-clés (dictionnaire).

Options de kwargs

Option

Type

Description

enable_prefetch

bool

Active le mode de prélecture. Désactivé par défaut.

prefetch_num

int

Nombre de fragments de prélecture. Par défaut : 3. Effectif uniquement en mode de prélecture.

chunk_size

int

Taille de chaque fragment de prélecture en MiB. Par défaut : 6. Effectif uniquement en mode de prélecture.

prefetch_threshold

int

Seuil de lecture séquentielle avant activation de la prélecture, en MiB. Par défaut : 20.

block_size

int

Taille d'un bloc. Valeur par défaut : None.

Paramètres de réponse

Paramètre

Type

Description

file

ReadOnlyFile

Instance ReadOnlyFile.

Méthodes courantes de ReadOnlyFile

Méthode

Description

close(self)

Ferme le fichier et libère les ressources, telles que la mémoire et les sockets actifs.

read(self, n=None)

Lit jusqu'à n octets depuis l'objet et renvoie les données lues.

seek(self, pos, whence=0)

Définit la position de lecture. Valeurs de whence : 0 (début), 1 (position actuelle), 2 (fin).

Stat() (os.FileInfo, error)

Récupère les informations de l'objet, y compris sa taille, sa date de dernière modification et ses métadonnées.

Important

Si plusieurs lectures désordonnées se produisent en mode de prélecture, le SDK revient automatiquement au mode mono-flux.

Exemples

Lire l'intégralité de l'objet en utilisant le mode mono-flux

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()

Lire l'intégralité de l'objet en utilisant le mode de prélecture

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()

Lire les données restantes à partir d'une position spécifique en utilisant la méthode 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()

Références

  • Documentation complète de référence de l'API : File-Like (GitHub).