Codex CLI Practical Examples

This section demonstrates various usage scenarios of Codex CLI through practical examples, helping you quickly master its application in real-world development.


Code Writing

Example 1: Creating a New Feature

Let Codex create a complete feature module for you:

Task

Create a Python function that accepts a list of strings and returns the longest string and its index position

Codex will generate code similar to the following:

Generated Code

def find_longest_string(strings):
    """
Find the longest string in a list of strings and its index position.

    Args:
strings: string list

    Returns:
tuple: (longest string, index position)
If the list is empty, return (None, -1)
    """

    if not strings:
        return None, -1

    longest = max(strings, key=len)
    index = strings.index(longest)

    return longest, index


# Test example
if __name__ == "__main__":
    test_list = ["apple", "banana", "cherry", "dragonfruit"]
    result, idx = find_longest_string(test_list)
    print(f"Longest string: {result}, index: {idx}")
    # Output: Longest string: dragonfruit, index: 3
The code generated by Codex includes detailed docstrings and test examples, and can be used directly.

Example 2: Refactoring Code

Ask Codex to refactor existing code:

Task

Refactor this function to use a generator:
def get_squares(n):
    result = []
    for i in range(n):
        result.append(i * i)
    return result

Codex will provide the refactored code:

Refactored Code

def get_squares(n):
    """
Generate the square numbers from 0 to n-1.

    Args:
n: number of square numbers to generate

    Yields:
int: square numbers from 0 to n-1
    """

    for i in range(n):
        yield i * i


# Usage example
for square in get_squares(5):
    print(square)
# Output: 0, 1, 4, 9, 16

Code Review

Example 1: Reviewing Code Issues

Ask Codex to review the code and suggest improvements:

Task

Review the issues in the following code:
def process_data(data):
    result = []
    for item in data:
        if item['type'] == 'a':
            result.append(item['value'] * 2)
        elif item['type'] == 'b':
            result.append(item['value'] + 10)
        elif item['type'] == 'c':
            result.append(item['value'])
    return result

Codex will analyze and provide a review report:

## 代码审查报告

### 问题
1. **缺少错误处理**:没有检查 item 是否包含必要的键
2. **类型不一致**:'c' 类型直接返回原值,而其他类型做了处理
3. **硬编码值**:乘数和加数应该作为参数或配置

### 改进建议
1. 添加默认字典或 try-except 处理
2. 统一处理逻辑
3. 将 magic numbers 提取为常量

Example 2: Using the /review Command

Use the built-in review command in Codex:

Task

/review src/

Codex will scan the entiresrc/directory and generate a comprehensive code review report.


Debugging and Troubleshooting

Example 1: Analyzing Error Messages

Give the error message to Codex for analysis:

Task

Help me analyze this error:
Traceback (most recent call last):
  File "app.py", line 42, in <module>
    main()
  File "app.py", line 38, in fetch_data()
  File "app.py", line 25, in fetch_data
    response = requests.get(url)
  File "/usr/lib/python3.10/site-packages/requests/api.py", line 88, in in get
    return session.request(method='GET', url=url, **kwargs)
  requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.example.com', port=443): Max retries exceeded

Codex will provide analysis and a solution:

## 错误分析

### 原因
网络连接问题 - 无法连接到 api.example.com

### 可能的原因
1. 网络不通
2. 域名解析失败
3. 服务器不可用
4. 防火墙阻止

### 建议的排查步骤
1. 检查网络连接:ping api.example.com
2. 验证域名解析:nslookup api.example.com
3. 检查端口是否开放:telnet api.example.com 443
4. 如果是本地开发,检查代理设置

Example 2: Adding Debug Logs

Ask Codex to add debugging code:

Task

Add debug logs to this function:
def calculate(a, b):
    return a + b * (a - b)

Codex will generate a version with debug logs:

Add Debug Logs

import logging

# Configure logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)


def calculate(a, b):
    """Calculation function with debug logs"""
    logger.debug(f"calculate called with a={a}, b={b}")

    result = a + b * (a - b)

    logger.debug(f"a + b = {a} + {b} = {a + b}")
    logger.debug(f"a - b = {a} - {b} = {a - b}")
    logger.debug(f"b * (a - b) = {b} * {a - b} = {b * (a - b)}")
    logger.debug(f"final result: {result}")

    return result

File Operations

Example 1: Batch Renaming Files

Task

Rename all files like image_001.jpg in the current directory to image-001.jpg (change underscores to hyphens)

Example 2: Creating a Project Structure

Task

Create a standard directory structure for a Flask project, including:
- app.py main file
- config.py configuration file
- requirements.txt
- tests/directory
- static/and templates/directory

Codex will create the complete project structure and generate all necessary files.

Codex will first list the files to be created, and then execute after confirmation.

Command Execution

Example 1: Running Tests

Task

Run the project's unit tests

Codex will automatically detect the project type and run the corresponding test command:

  • Python project: pytest or unittest
  • Node.js project: npm test or yarn test
  • Rust project: cargo test

Example 2: Git Operations

Task

Create a Git commit that includes all changes and uses an appropriate commit message

Codex will analyze all uncommitted changes, then execute:

  1. git status- View changes
  2. git diff- Review specific modifications
  3. git add -A- Add all files
  4. git commit -m "..."- Create commit
For Git operations, Codex will first show the changes, and only execute after confirmation.

Project Analysis

Example 1: Understanding the Project Structure

Task

Analyze the architecture and tech stack of this project

Codex will check the project's:

  • Configuration files (package.json, Cargo.toml, requirements.txt, etc.)
  • Directory structure
  • Main source files

Then provide a detailed analysis report.

Example 2: Finding Dependencies

Task

Find which files reference the auth.py file

Plan Mode

Use the /plan command to plan complex tasks:

Task

/Plan to add user authentication to this React project, including login, registration, and JWT verification

Codex will first show a detailed implementation plan:

## 实施计划:用户认证功能

### 步骤 1:准备
- 创建用户模型
- 安装认证依赖(jsonwebtoken, bcryptjs)

### 步骤 2:后端实现
- 创建 /api/auth/register 端点
- 创建 /api/auth/login 端点
- 实现 JWT 生成和验证中间件

### 步骤 3:前端实现
- 创建登录表单组件
- 创建注册表单组件
- 添加认证状态管理

### 步骤 4:测试
- 编写后端单元测试
- 测试前端表单交互

是否确认执行此计划?
[Y] 确认 [N] 取消 [M] 修改
Plan mode lets you understand Codex's complete approach before execution, avoiding unnecessary rework.

Comprehensive Examples

A complete workflow example:

Complete Workflow

# 1. Start a new session
/new

# 2. Understand the project
What framework does this project use? What are the main features?

# 3. Add a new feature
InusersAdd a feature to send verification codes in the module; need to consider:
- Verification code generation (6digits)
- 60Cannot resend within seconds
- Verification code10valid for minutes

# 4. Test
Run relevant tests to ensure the functionality works correctly

# 5. Code review
/review

This example demonstrates a typical development workflow: understand the project → implement the feature → test → review.


Quick Operations Summary

ScenarioCommand to use
Write a functionJust describe the requirement
Review code/review or "help me review..."
Debug issuesPaste the error message and request analysis
Execute commandStart with !
Complex task planning/plan + task description
Understand code"What does this function do?"
Practice makes perfect. Using Codex more will make you more skilled, and your efficiency in writing code will greatly improve.
other extensions