Codex CLI Practical Examples
This section demonstrates various use cases of Codex CLI through practical examples, helping you quickly master its application in real development.
Code writing
Example 1: Creating a new feature
Have Codex create a complete feature module for you:
Task
Create a Python function that takes a list of strings and returns the longest string and its index
Codex generates 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: a list of strings
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
)
(
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 provides the refactored code:
Code after refactoring
def
get_squares
(
n
)
:
"""
Generate the squares of numbers from 0 to n-1.
Args:
n: the number of squares to generate
Yields:
int: the squares from 0 to n-1
"""
for
i
in
range
(
n
)
:
yield
i * i
Usage examples
for
square
in
get_squares
(
5
)
:
(
square
)
Output: 0, 1, 4, 9, 16
Code review
Example 1: Reviewing code issues
Ask Codex to review code and suggest improvements:
Task
Review the following code for issues:
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 analyzes it and provides 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 scans the entire src/ directory and generates a comprehensive code review report.
Debugging and troubleshooting
Example 1: Analyzing error messages
Give the error message to Codex to analyze:
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 provides analysis and solutions:
## Error Analysis
### 原因
网络连接问题 - 无法连接到 api.example.com
### 可能的原因
1. 网络不通
2. 域名解析失败
3. 服务器不可用
4. 防火墙阻止
### Suggested troubleshooting steps
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 debug code:
Task
Add debug logs to this function:
def calculate
(
a, b
)
:
return
a + b
(
a - b
)
Codex generates 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
)
:
"""A computation 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 creates the complete project structure and generates all necessary files.
Codex first lists the files to be created and executes after confirmation.
Command execution
Example 1: Running tests
Task
Run the project's unit tests
Codex automatically detects the project type and runs 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 with an appropriate commit message
Codex analyzes all uncommitted changes, then performs the following:
git status- View changesgit diff- Review specific changesgit add -A- Stage all filesgit commit -m "..."- Create the commit
For Git operations, Codex first shows the changes and only executes after confirmation.
Project Analysis
Example 1: Understanding the Project Structure
Task
Analyze the architecture and tech stack of this project
Codex examines the project's:
- Configuration files (package.json, Cargo.toml, requirements.txt, etc.)
- Directory structure
- Main source files
Then it provides 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 Add user authentication to this React project, including login, registration, and JWT verification
Codex first presents a detailed implementation plan:
## Implementation Plan: User Authentication Feature
### Step 1: Preparation
- 创建用户模型
- 安装认证依赖(jsonwebtoken, bcryptjs)
### Step 2: Backend Implementation
- 创建 /api/auth/register 端点
- 创建 /api/auth/login 端点
- 实现 JWT 生成和验证中间件
### Step 3: Frontend Implementation
- 创建登录表单组件
- 创建注册表单组件
- 添加认证状态管理
### Step 4: Test
- 编写后端单元测试
- 测试前端表单交互
是否确认执行此计划?
[Y] 确认 [N] 取消 [M] 修改
Plan mode lets you understand Codex's complete approach before execution, avoiding unnecessary rework.
Comprehensive Example
An example of a complete workflow:
Complete Workflow
1. Start a New Session
/
new
2. Understand the Project
What framework does this project use? What are its main features?
3. Add a New Feature
in
users
Add a verification code sending feature to the module, considering:
- Verification code generation (
6
digits)
60
Cannot resend within the specified number of seconds
- Verification code
10
valid for the specified number of minutes
4. Testing
Run relevant tests to ensure the feature works properly
5. Code Review
/
review
This example shows a typical development workflow: understand the project → implement the feature → test → review.
Quick Actions Summary
| Scenario | Command Used |
|---|---|
| Write a function | Just describe the requirement |
| Review code | /review or "Help me review..." |
| Debugging problems | Paste the error message and request analysis |
| Execute the command | Start with ! |
| Plan a complex task | /plan + task description |
| Understand code | "What does this function do?" |
Practice makes perfect: the more you use Codex, the more proficient you become, and your coding efficiency improves significantly.