

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 `ListShards` 用 Amazon SDK 或 CLI

以下代码示例显示了如何使用 `ListShards`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](example_kinesis_Scenario_GettingStarted_section.md) 

------
#### [ CLI ]

**Amazon CLI**  
**列出数据流中的分片**  
以下 `list-shards` 示例列出指定流中从 ID 紧接指定 `exclusive-start-shard-id` 的 `shardId-000000000000` 后的分片开始的所有分片。  

```
aws kinesis list-shards \
    --stream-name {{samplestream}} \
    --exclusive-start-shard-id {{shardId-000000000000}}
```
输出：  

```
{
    "Shards": [
        {
            "ShardId": "shardId-000000000001",
            "HashKeyRange": {
                "StartingHashKey": "113427455640312821154458202477256070485",
                "EndingHashKey": "226854911280625642308916404954512140969"
            },
            "SequenceNumberRange": {
                "StartingSequenceNumber": "49600871682979337187563555549332609155523708941634633746"
            }
        },
        {
            "ShardId": "shardId-000000000002",
            "HashKeyRange": {
                "StartingHashKey": "226854911280625642308916404954512140970",
                "EndingHashKey": "340282366920938463463374607431768211455"
            },
            "SequenceNumberRange": {
                "StartingSequenceNumber": "49600871683001637932762086172474144873796357303140614178"
            }
        }
    ]
}
```
有关更多信息，请参阅《Amazon Kinesis Data Streams 开发人员指南》**中的[列出分片](https://docs.amazonaws.cn/streams/latest/dev/kinesis-using-sdk-java-list-shards.html)。  
+  有关 API 的详细信息，请参阅 [ListShards](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/list-shards.html) 在 *Amazon CLI 命令参考*。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多关于 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)中查找完整示例，了解如何进行设置和运行。

```python
    def list_shards(self, stream_name, max_wait=30, poll_interval=2):
        """
        Lists the shards in a Kinesis data stream.

        A freshly created stream can report ACTIVE via DescribeStreamSummary
        before its shards are listable. Because ListShards is eventually
        consistent, it may briefly raise ResourceInUseException ("in state
        CREATING") or ResourceNotFoundException. This method retries on those
        errors until the shards become available or ``max_wait`` elapses.

        :param stream_name: The name of the stream whose shards to list.
        :param max_wait: Maximum seconds to retry while the stream is still
                         settling after creation.
        :param poll_interval: Seconds between retries.
        :return: A list of shard dictionaries.
        """
        elapsed = 0
        while True:
            try:
                shards = list()
                response = self.kinesis_client.list_shards(StreamName=stream_name)
                shards.extend(response.get("Shards", list()))
                while "NextToken" in response:
                    response = self.kinesis_client.list_shards(
                        NextToken=response["NextToken"]
                    )
                    shards.extend(response.get("Shards", list()))
                logger.info(
                    "Listed %s shard(s) for stream '%s'.", len(shards), stream_name
                )
                return shards
            except ClientError as err:
                code = err.response["Error"]["Code"]
                retryable = ("ResourceInUseException", "ResourceNotFoundException")
                if code in retryable and elapsed < max_wait:
                    logger.info(
                        "Stream '%s' not ready for ListShards yet. Retrying...",
                        stream_name,
                    )
                    time.sleep(poll_interval)
                    elapsed += poll_interval
                    continue
                if code == "ResourceNotFoundException":
                    logger.error(
                        "Stream '%s' not found. Verify the stream is ACTIVE.",
                        stream_name,
                    )
                raise
```
+  有关 API 的详细信息，请参阅 [ListShards](https://docs.amazonaws.cn/goto/boto3/kinesis-2013-12-02/ListShards) 在 *Amazon 适用于 Python 的 SDK (Boto3) API 参考*。

------

如需查看完整清单 Amazon SDK 开发者指南和代码示例，请参阅 [将此服务与 Amazon SDK](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。