This section demonstrates various use cases of Codex CLI through practical examples to help you quickly master its application in real-world development.
\\n\\n\\n\\n
Code Writing
\\n\\nExample 1: Creating New Features
\\n\\nHave Codex create a complete feature module for you:
\\n\\nTask
\\n\\nCreate a Python function that accepts a list of strings and returns the longest string and its index position
\\n\\nCodex will generate code similar to the following:
\\n\\nGenerated Code
\\n\\ndef find_longest_string(strings):\\n """\\n Find the longest string in a List of strings and its Index position.\\n \\n Args:\\n strings: List of strings\\n \\n Returns:\\n tuple: (Longest string, Indexposition)\\n If the list is empty, return (None, -1)\\n """\\n if not strings:\\n return None, -1\\n \\n longest = max(strings, key=len)\\n index = strings.index(longest)\\n \\n return longest, index\\n\\n# TestExample\\nif __name__ == "__main__":\\n test_list = ["apple", "banana", "cherry", "dragonfruit"]\\n result, idx = find_longest_string(test_list)\\n print(f"Longest string: {result}, Index: {idx}")\\n # Output: Longest string: dragonfruit, Index: 3\\n\\n\\n\\n\\n\\nCodex-generated code includes detailed documentation comments and test examples, ready for immediate use.
\\n
Example 2: Refactoring Code
\\n\\nRequest Codex to refactor existing code:
\\n\\nTask
\\n\\nRefactor this function to use a generator:
\\n\\ndef get_squares(n):\\n result = []\\n for i in range(n):\\n result.append(i * i)\\n return result\\n\\n\\nCodex will provide the refactored code:
\\n\\nRefactored Code
\\n\\ndef get_squares(n):\\n """\\n Generate from 0 to n-1 square numbers ofγ\\n \\n Args:\\n n: Count of generated square numbers\\n \\n Yields:\\n int: 0 to n-1 square numbers of\\n """\\n for i in range(n):\\n yield i * i\\n\\n# Usage example\\nfor square in get_squares(5):\\n print(square)\\n# Output: 0, 1, 4, 9, 16\\n\\n\\n\\n\\n
Code Review
\\n\\nExample 1: Reviewing Code Issues
\\n\\nRequest Codex to review code and provide improvement suggestions:
\\n\\nTask
\\n\\nReview the issues in the following code:
\\n\\ndef process_data(data):\\n result = []\\n for item in data:\\n if item['type'] == 'a':\\n result.append(item['value'] * 2)\\n elif item['type'] == 'b':\\n result.append(item['value'] + 10)\\n elif item['type'] == 'c':\\n result.append(item['value'])\\n return result\\n\\n\\nCodex will analyze and provide a review report:
\\n\\nCode Review Report
\\n\\nIssues
\\n\\n- \\n
- Missing error handling: No check whether item contains required keys \\n
- Inconsistent types: 'c' type returns the original value directly, while other types are processed \\n
- Hard-coded values: Multipliers and addends should be parameters or configurations \\n
Improvement Suggestions
\\n\\n- \\n
- Add default dictionary or try-except handling \\n
- Unify processing logic \\n
- Extract magic numbers as constants \\n
Example 2: Using the /review Command
\\n\\nUse the built-in review command in Codex:
\\n\\nTask
\\n\\n/review src/\\n\\n\\nCodex will scan the entire src/ directory and generate a comprehensive code review report.
\\n\\n
Debugging and Troubleshooting
\\n\\nExample 1: Analyzing Error Messages
\\n\\nGive error messages to Codex for analysis:
\\n\\nTask
\\n\\nHelp me analyze this error:
\\n\\nTraceback (most recent call last):\\n File "app.py", line 42, in <module>\\n main()\\n File "app.py", line 38, in fetch_data()\\n File "app.py", line 25, in fetch_data\\n response = requests.get(url)\\n File "/usr/lib/python3.10/site-packages/requests/api.py", line 88, in in get\\n return session.request(method='GET', url=url, **kwargs)\\nrequests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.example.com', port=443): Max retries exceeded\\n\\n\\nCodex will provide analysis and solutions:
\\n\\nError Analysis
\\n\\nCause
\\n\\nNetwork connection issue - unable to connect to api.example.com
\\n\\nPossible Reasons
\\n\\n- \\n
- Network is unreachable \\n
- Domain name resolution failure \\n
- Server is unavailable \\n
- Firewall blocking \\n
Suggested Troubleshooting Steps
\\n\\n- \\n
- Check network connection:
ping api.example.com\\n - Verify domain resolution:
nslookup api.example.com\\n - Check if port is open:
telnet api.example.com 443\\n - If local development, check proxy settings \\n
Example 2: Adding Debug Logs
\\n\\nRequest Codex to add debug code:
\\n\\nTask
\\n\\nAdd debug logs to this function:
\\n\\ndef calculate(a, b):\\n return a + b * (a - b)\\n\\n\\nCodex will generate a version with debug logs:
\\n\\nAdding Debug Logs
\\n\\nimport logging\\n\\n# Configure logging\\nlogging.basicConfig(level=logging.DEBUG)\\nlogger = logging.getLogger(__name__)\\n\\ndef calculate(a, b):\\n """Calculation function with debug logs"""\\n logger.debug(f"calculate called with a={a}, b={b}")\\n \\n result = a + b * (a - b)\\n \\n logger.debug(f"a + b = {a} + {b} = {a + b}")\\n logger.debug(f"a - b = {a} - {b} = {a - b}")\\n logger.debug(f"b * (a - b) = {b} * {a - b} = {b * (a - b)}")\\n logger.debug(f"final result: {result}")\\n \\n return result\\n\\n\\n\\n\\n
File Operations
\\n\\nExample 1: Batch Renaming Files
\\n\\nTask
\\n\\nRename all files like image_001.jpg in the current directory to image-001.jpg (replace underscores with hyphens)
Example 2: Creating Project Structure
\\n\\nTask
\\n\\nCreate a standard directory structure for a Flask project, including:
\\n\\n- \\n
- app.py main file \\n
- config.py configuration file \\n
- requirements.txt \\n
- tests/ directory \\n
- static/ and templates/ directories \\n
Codex will create the complete project structure and generate all necessary files.
\\n\\n\\n\\n\\nCodex will first list the files to be created and execute after confirmation.
\\n
\\n\\n
Command Execution
\\n\\nExample 1: Running Tests
\\n\\nTask
\\n\\nRun the project's unit tests
\\n\\nCodex will automatically detect the project type and run the corresponding test commands:
\\n\\n- \\n
- Python projects: pytest or unittest \\n
- Node.js projects: npm test or yarn test \\n
- Rust projects: cargo test \\n
Example 2: Git Operations
\\n\\nTask
\\n\\nCreate a Git commit with all changes and an appropriate commit message
\\n\\nCodex will analyze all uncommitted changes, then execute:
\\n\\n- \\n
git status- view changes \\ngit diff- review specific modifications \\ngit add -A- add all files \\ngit commit -m "..."- create commit \\n
\\n\\n\\nFor Git operations, Codex will first display the changes and execute after confirmation.
\\n
\\n\\n
Project Analysis
\\n\\nExample 1: Understanding Project Structure
\\n\\nTask
\\n\\nAnalyze this project's architecture and technology stack
\\n\\nCodex will check the project's:
\\n\\n- \\n
- Configuration files (package.json, Cargo.toml, requirements.txt, etc.) \\n
- Directory structure \\n
- Main source files \\n
Then provide a detailed analysis report.
\\n\\nExample 2: Finding Dependencies
\\n\\nTask
\\n\\nFind which files reference auth.py
\\n\\n\\n\\n
Plan Mode
\\n\\nUse the /plan command for planning complex tasks:
Task
\\n\\n/plan Add user authentication to this React project, including login, registration, and JWT verification\\n\\n\\nCodex will first display a detailed implementation plan:
\\n\\nImplementation Plan: User Authentication Feature
\\n\\nStep 1: Preparation
\\n\\n- \\n
- Create user model \\n
- Install authentication dependencies (jsonwebtoken, bcryptjs) \\n
Step 2: Backend Implementation
\\n\\n- \\n
- Create /api/auth/register endpoint \\n
- Create /api/auth/login endpoint \\n
- Implement JWT generation and verification middleware \\n
Step 3: Frontend Implementation
\\n\\n- \\n
- Create login form component \\n
- Create registration form component \\n
- Add authentication state management \\n
Step 4: Testing
\\n\\n- \\n
- Write backend unit tests \\n
- Test frontend form interactions \\n
Confirm execution of this plan?
\\n Confirm Cancel Modify
\\n\\n\\nPlan mode lets you understand Codex's complete thought process before execution, avoiding unnecessary rework.
\\n
\\n\\n
Comprehensive Example
\\n\\nA complete workflow example:
\\n\\nComplete Workflow
\\n\\n# 1. Start new session\\n/new\\n\\n# 2. Understand the project\\nWhat framework does this project use? What are its main features?\\n\\n# 3. Add new feature\\nAdd a verification code sending feature to the users module, considering:\\n- Verification code generation (6 digits)\\n- 60 Cannot be resent within seconds\\n- Verification code valid for 10 minutes\\n\\n# 4. Test\\nRun relevant Tests to ensure proper functionality.\\n\\n# 5. Code review\\n/review\\n\\n\\nThis example demonstrates a typical development workflow: understand project β implement feature β test β review.
\\n\\n\\n\\n
Quick Operations Summary
\\n\\n| Scenario | \\nCommand to Use | \\n
|---|---|
| Write a function | \\nDescribe requirements directly | \\n
| Review code | \\n/review or "help me review..." | \\n
| Debug issues | \\nPaste error message and request analysis | \\n
| Execute commands | \\nStart with ! | \\n
| Complex task planning | \\n/plan + task description | \\n
| Understand code | \\n"What does this function do?" | \\n
\\nPractice makes perfect. The more you use Codex, the more proficient you'll become, and your coding efficiency will improve significantly.
\\n
YouTip