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
Codex will generate code similar to the following:
Generated Code
"""
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
def get_squares(n):
result = []
for i in range(n):
result.append(i * i)
return result
Codex will provide the refactored code:
Refactored Code
"""
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
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
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
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
def calculate(a, b):
return a + b * (a - b)
Codex will generate a version with debug logs:
Add Debug Logs
# 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
Example 2: Creating a Project Structure
Task
- 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
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
Codex will analyze all uncommitted changes, then execute:
git status- View changesgit diff- Review specific modificationsgit add -A- Add all filesgit 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
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
Plan Mode
Use the /plan command to plan complex tasks:
Task
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
/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
| Scenario | Command to use |
|---|---|
| Write a function | Just describe the requirement |
| Review code | /review or "help me review..." |
| Debug issues | Paste the error message and request analysis |
| Execute command | Start 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