Agent skill

Document Python Direct Exec

by HKUDS in HKUDS/OpenSpace

Use direct Python execution for reliable spreadsheet and document/PDF generation operations

MITAuto-check passedDocuments & Office

Install Document Python Direct Exec

skills CLI
$ npx skills add HKUDS/OpenSpace --skill document-python-direct-exec -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install HKUDS/OpenSpace document-python-direct-exec --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/HKUDS/OpenSpace.git skills-src && mkdir -p .claude/skills && cp -r skills-src/benchmarks/gdpval/skills/spreadsheet-direct-python-merged-343937 .claude/skills/document-python-direct-exec && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
document-python-direct-exec
GitHub stars
7.7k
Token cost
~2.9k tokens
SKILL.md length
732 words
Files
2
Skills in repo
199
Repo updated
First seen
Licence
MIT

At a glance

Use direct Python execution for reliable spreadsheet and document/PDF generation operations

  • Works in 9 steps: Prefer file-based execution for complex… → Import only needed libraries to reduce… → Print clear success/error messages for… → …
  • Tasks that involve Excel spreadsheets
  • SKILL.md covers When to Use This Skill, Why Direct Execution?, How to Use and Spreadsheet Examples, plus 7 more sections
  • Calls python3 and pip

What it does

Document Python Direct Exec is an agent skill from HKUDS/OpenSpace. Use direct Python execution for reliable spreadsheet and document/PDF generation operations

Its SKILL.md is about 2.9k tokens, which your agent loads only when the skill is triggered. The skill folder holds 1 other file.

It sits in Documents & Office, covering Excel spreadsheets and PDF. It works with Python. The repository describes itself as: "OpenSpace: The Skill Management Layer for AI Agents" -- https://open-space.cloud/. The licence is MIT.

When your agent uses it

  • Tasks that involve Excel spreadsheets
  • Tasks that involve PDF

Example prompts

  • “/document-python-direct-exec”

Requirements

  • Python 3

Workflow steps

9 steps, taken from the first numbered list in SKILL.md.

  1. Prefer file-based execution for complex scripts: write to .py file first, then execute via run_shell
  2. Import only needed libraries to reduce execution time and avoid dependency conflicts
  3. Print clear success/error messages for debugging
  4. Save intermediate results for complex multi-step transformations
  5. Test with small data before scaling to large documents or spreadsheets
  6. Use appropriate libraries for the task: pandas/openpyxl for spreadsheets, reportlab/fpdf for PDFs
  7. Clean up temporary script files after execution if they won't be reused
  8. Use absolute paths or verify working directory to avoid file not found errors
  9. For PDFs: Build content in memory first, then write to file atomically

What it can do on your machine

Read from SKILL.md and the folder at commit 3827781. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • python3
    • pip

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md. Its commands use pip, which can reach the network depending on how they are called.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Document Python Direct Exec loads about 2.9k tokens when it runs. Until then it costs about 30 tokens; SKILL.md has 732 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~30
When it runs · the whole SKILL.md, loaded when a task matches
~2.9k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from HKUDS/OpenSpace at commit 3827781, republished under its MIT licence (© HKUDS). 732 words, ~2,939 tokens.

Download SKILL.mdSave it as .claude/skills/document-python-direct-exec/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from GitHub.
name
document-python-direct-exec
description
Use direct Python execution for reliable spreadsheet and document/PDF generation operations

Direct Python Execution for Spreadsheet and Document Tasks

When to Use This Skill

Use direct run_shell with Python scripts for structured document operations when:

  • Spreadsheets: Reading or writing complex Excel files with multiple sheets, applying formulas, formatting, or data transformations
  • PDFs: Generating PDF checklists, reports, invoices, or forms with precise layout control
  • Documents: Creating Word documents, HTML reports, or other structured output formats
  • Complex Operations: The task involves multiple steps that could exceed agent step limits
  • Precision Needed: You need precise control over error handling, debugging, and library imports

Why Direct Execution?

The shell_agent tool can:

  • Hit maximum step limits on complex multi-step operations
  • Produce unexplained errors on formatting operations
  • Fail on intricate reads/writes due to iterative parsing
  • Fail to parse heredoc syntax correctly, causing 'unknown error' failures

Direct run_shell with Python is more reliable because it:

  • Executes in a single step with no iteration limits
  • Provides clearer, immediate error messages
  • Handles complex operations without step constraints
  • Gives full control over library imports and execution flow
  • Writing scripts to .py files first avoids shell_agent parsing issues with heredocs

How to Use

For complex multi-line scripts, especially when using shell_agent as executor:

bash
# Step 1: Write the Python script to a file
cat > process_document.py << 'EOF'
# Your document/spreadsheet code here
EOF

# Step 2: Execute the script
python3 process_document.py
Alternative Pattern: Inline Heredoc (Simple Scripts Only)

For short, simple scripts when NOT using shell_agent as the executor:

bash
python3 << 'EOF'
# Your code here
EOF

Spreadsheet Examples

Example 1: Read and Transform Excel Data
python
import pandas as pd

# Load data from specific sheet
df = pd.read_excel('input.xlsx', sheet_name='Revenue')

# Apply transformations
df['Net_Revenue'] = df['Gross_Revenue'] * (1 - df['Tax_Rate'])

# Save results
df.to_excel('output.xlsx', index=False, sheet_name='Processed')
Example 2: Multi-Sheet Operations with openpyxl
python
from openpyxl import load_workbook

wb = load_workbook('tour_data.xlsx')

# Iterate through sheets
for sheet_name in wb.sheetnames:
    ws = wb[sheet_name]
    # Apply formatting or calculations
    for row in ws.iter_rows(min_row=2, max_col=5):
        # Process cells
        pass

wb.save('tour_data_processed.xlsx')
Example 3: Complex Formatting Operations
python
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment

wb = load_workbook('report.xlsx')
ws = wb.active

# Apply header styling
header_fill = PatternFill(start_color='4472C4', fill_type='solid')
header_font = Font(bold=True, color='FFFFFF')

for cell in ws[1]:
    cell.fill = header_fill
    cell.font = header_font
    cell.alignment = Alignment(horizontal='center')

wb.save('report_formatted.xlsx')

PDF Generation Examples

Example 4: Generate PDF Checklist with ReportLab
python
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch

def create_checklist(pdf_path, items):
    c = canvas.Canvas(pdf_path, pagesize=letter)
    width, height = letter
    
    # Title
    c.setFont("Helvetica-Bold", 16)
    c.drawString(1*inch, height - 1*inch, "Safety Checklist")
    
    # Checklist items
    c.setFont("Helvetica", 12)
    y_position = height - 1.5*inch
    
    for i, item in enumerate(items, 1):
        checkbox_x = 1*inch
        text_x = 1.3*inch
        c.drawString(checkbox_x, y_position, "☐")  # Empty checkbox
        c.drawString(text_x, y_position, f"{i}. {item}")
        y_position -= 0.3*inch
        
        # New page if needed
        if y_position < 1*inch:
            c.showPage()
            y_position = height - 1*inch
    
    c.save()
    print(f"Created checklist: {pdf_path}")

# Usage
items = [
    "Verify equipment is powered off",
    "Check safety gear is available",
    "Inspect work area for hazards",
    "Confirm emergency contacts are posted"
]
create_checklist('safety_checklist.pdf', items)
Example 5: Generate PDF Report with Tables
python
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch

def create_report(pdf_path, title, data, column_headers):
    doc = SimpleDocTemplate(pdf_path, pagesize=letter,
                           rightMargin=0.75*inch, leftMargin=0.75*inch,
                           topMargin=0.75*inch, bottomMargin=0.75*inch)
    
    elements = []
    styles = getSampleStyleSheet()
    
    # Title
    title_style = ParagraphStyle('CustomTitle', parent=styles['Heading1'],
                                 fontSize=18, spaceAfter=30, alignment=1)
    elements.append(Paragraph(title, title_style))
    elements.append(Spacer(1, 0.25*inch))
    
    # Table
    table_data = [column_headers] + data
    table = Table(table_data, colWidths=[2*inch, 1.5*inch, 1.5*inch])
    
    # Table styling
    table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#4472C4')),
        ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('FONTSIZE', (0, 0), (-1, 0), 12),
        ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
        ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#D6DCE4')]),
        ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
    ]))
    
    elements.append(table)
    doc.build(elements)
    print(f"Created report: {pdf_path}")

# Usage
headers = ['Item', 'Quantity', 'Status']
data = [
    ['Widget A', '150', 'Complete'],
    ['Widget B', '200', 'In Progress'],
    ['Widget C', '75', 'Pending']
]
create_report('status_report.pdf', 'Weekly Status Report', data, headers)
Example 6: PDF with Images and Text (FPDF Alternative)
python
from fpdf import FPDF

class PDF(FPDF):
    def header(self):
        self.set_font('Arial', 'B', 15)
        self.cell(0, 10, 'Project Documentation', 0, 1, 'C')
        self.ln(10)
    
    def footer(self):
        self.set_y(-15)
        self.set_font('Arial', 'I', 8)
        self.cell(0, 10, f'Page {self.page_no()}', 0, 0, 'C')

def create_document(pdf_path, title, sections):
    pdf = PDF()
    pdf.add_page()
    pdf.set_font('Arial', 'B', 16)
    pdf.cell(0, 10, title, 0, 1, 'L')
    pdf.ln(5)
    
    pdf.set_font('Arial', '', 12)
    for section in sections:
        pdf.set_font('Arial', 'B', 14)
        pdf.cell(0, 10, section['title'], 0, 1)
        pdf.set_font('Arial', '', 12)
        pdf.multi_cell(0, 6, section['content'])
        pdf.ln(5)
    
    pdf.output(pdf_path)
    print(f"Created document: {pdf_path}")

# Usage
sections = [
    {'title': 'Overview', 'content': 'This document provides...'},
    {'title': 'Requirements', 'content': 'The following requirements...'},
    {'title': 'Timeline', 'content': 'Project phases are...'}
]
create_document('project_doc.pdf', 'Project Alpha', sections)

Error Handling Pattern

python
import sys
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

try:
    c = canvas.Canvas('output.pdf', pagesize=letter)
    
    # Your document operations here
    c.drawString(100, 750, "Document content")
    
    c.save()
    print("Success: PDF created")
    
except Exception as e:
    print(f"Error: {str(e)}", file=sys.stderr)
    sys.exit(1)

Best Practices

  1. Prefer file-based execution for complex scripts: write to .py file first, then execute via run_shell
  2. Import only needed libraries to reduce execution time and avoid dependency conflicts
  3. Print clear success/error messages for debugging
  4. Save intermediate results for complex multi-step transformations
  5. Test with small data before scaling to large documents or spreadsheets
  6. Use appropriate libraries for the task: pandas/openpyxl for spreadsheets, reportlab/fpdf for PDFs
  7. Clean up temporary script files after execution if they won't be reused
  8. Use absolute paths or verify working directory to avoid file not found errors
  9. For PDFs: Build content in memory first, then write to file atomically

When NOT to Use This Skill

  • Simple single-cell reads/writes (use shell_agent or basic commands)
  • Operations that require interactive user input
  • Tasks where you need the agent to iteratively refine the approach
  • When the target format has a simpler CLI tool available (e.g., pandoc for document conversion)
Show full SKILL.md (310 more words)Show less

Common Libraries

LibraryBest For
openpyxlReading/writing .xlsx files, formatting, formulas
pandasData manipulation, analysis, merging datasets
xlrdReading older .xls files (read-only)
xlsxwriterCreating new .xlsx files with advanced formatting
reportlabProfessional PDF generation with precise layout control
fpdfSimple PDF creation, easier learning curve
python-docxCreating and editing Word documents
weasyprintHTML/CSS to PDF conversion

Troubleshooting

Issue: Heredoc syntax fails with 'unknown error' when using shell_agent

  • Solution: Write the Python script to a .py file first, then execute it with python3 script.py. This pattern is significantly more reliable than inline heredoc execution when shell_agent is the executor.

Issue: FileNotFoundError

  • Solution: Verify the file path is absolute or relative to the working directory. Use os.getcwd() to confirm current directory if needed.

Issue: PermissionError

  • Solution: Ensure the file is not open in another application. On Linux/Mac, check file permissions with ls -la.

Issue: ModuleNotFoundError

  • Solution: Install required libraries first: pip install reportlab openpyxl pandas. Some environments may need pip3 instead.

Issue: MemoryError on large files

  • Solution: Process data in chunks using pandas chunksize parameter. For PDFs, create multi-page documents instead of single massive pages.

Issue: Formatting not applying (spreadsheets)

  • Solution: Ensure you're modifying cell styles before saving, and use .copy() for style objects to avoid reference issues.

Issue: PDF text rendering incorrectly

  • Solution: Check font encoding. For special characters, use Unicode-compatible fonts or escape special characters. ReportLab supports UTF-8 with proper font configuration.

Issue: PDF layout breaks across pages

  • Solution: Use ReportLab's flowable elements (Paragraph, Spacer) which handle page breaks automatically, or manually check y-position and call showPage() when needed.

Quick Reference: PDF vs Spreadsheet Choice

NeedRecommended Library
Data analysis, calculationspandas + Excel output
Complex cell formattingopenpyxl
Professional reports with tablesreportlab (PDF)
Simple checklists, formsfpdf or reportlab
Word document outputpython-docx
HTML to PDFweasyprint
Both data + formatted outputGenerate data with pandas, format with reportlab

© HKUDS, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 1 other file in benchmarks/gdpval/skills/spreadsheet-direct-python-merged-343937 of HKUDS/OpenSpace.

  • SKILL.md
  • .skill_id

Open the folder on GitHubat commit 3827781

Compare with similar skills

Document Python Direct Exec next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Document Python Direct Exec compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Document Python Direct Exec this skillHKUDS/OpenSpace7.7k—~2.9kAutomated safety check: PassMIT
Instrument Data To Allotropeaws-samples/amazon-bedrock-agents-healthcare-lifesciences2742 repos~2.7kAutomated safety check: PassApache-2.0
Doc Cleanernotoriouslab/doc-cleaner309—~712Automated safety check: PassMIT
MineruNebutra/MinerU-Skill122—~504Automated safety check: PassMIT
Office To Mdshuyu-labs/WebCode278—~1kAutomated safety check: NotesCustom licence
Exam IngestZeKaiNie/universal-examprep-skill301—~5.6kAutomated safety check: PassMIT

Similar skills

  • Instrument Data To Allotrope

    aws-samples/amazon-bedrock-agents-healthcare-lifesciences

    Official

    Convert laboratory instrument output files (PDF, CSV, Excel, TXT) to Allotrope Simple Model (ASM) JSON format or flattened 2D CSV.

    274 GitHub starsUsed in 2 repos~2.7k tokens
    Documents & OfficeAuto-check passed
  • Doc Cleaner

    notoriouslab/doc-cleaner

    Convert PDF, DOCX, XLSX, and text files to clean, structured Markdown.

    309 GitHub stars~712 tokensUpdated 1 mo ago
    Documents & OfficeAuto-check passed
  • Mineru

    Nebutra/MinerU-Skill

    An AI-Native skill for parsing PDF / Office / image files into Markdown with MinerU — a fast, zero-config document parser for AI agents.

    122 GitHub stars~504 tokensUpdated 13 days ago
    Documents & OfficeAuto-check passed
  • Office To Md

    shuyu-labs/WebCode

    Convert Office documents (Word, Excel, PowerPoint, PDF) to Markdown format.

    278 GitHub stars~1k tokensUpdated 3 mo ago
    Documents & OfficeAuto-check: notes
  • Exam Ingest

    ZeKaiNie/universal-examprep-skill

    从学生上传的课件/大纲/老师勾的重点/真题,一键初始化并验证备考工作区:解析 PDF、DOCX、PPTX、 XLSX、常见独立图片与 txt/md,建立分章节 LLM Wiki、标准题库、结构化接管队列与进度状态;仅在 Python 确实无法运行时 明确降级为手动写盘。当工作区尚未建立、资料发生变化、或建库 readiness 被阻断时使用。

    301 GitHub stars~5.6k tokensUpdated 9 days ago
    Documents & OfficeAuto-check passed
  • Cc Streaming Export Safety

    doccker/cc-use-exp

    当实现用户驱动的大文件导出或批量序列化(Excel/CSV/JSON/JSONL/PDF,数据量未知或超过 1 万行/10 MB)时触发;普通小文件下载、静态资源下载、非导出 Writer/Report 类不触发。防止 OOM、临时文件残留、同步导出阻塞 HTTP 线程和表格公式注入。

    1.1k GitHub stars~2.2k tokensUpdated 1 mo ago
    Documents & OfficeAuto-check passed

More from HKUDS/OpenSpace

All 199 skills in this repo
  • Walks through producing a master audio track plus stems in Python, from checking a reference file and timing sections by BPM to effects, a zip archive and final verification.

    7.7k GitHub stars~2.9k tokensUpdated 1 mo ago
    Auto-check passed
  • Handle cascading data retrieval tool failures by falling back to embedded knowledge generation

    7.7k GitHub stars~765 tokensUpdated 1 mo ago
    Auto-check passed
  • Gives an agent a workaround when its code-execution sandbox keeps failing: save the Python script to a file and run it through the shell instead.

    7.7k GitHub stars~588 tokensUpdated 1 mo ago
    Auto-check passed
  • A recovery routine for agents whose sandboxed code runner keeps failing: save the Python script to disk, then run it through the shell and read the output.

    7.7k GitHub stars~652 tokensUpdated 1 mo ago
    Auto-check passed
  • Fallback ladder for failed sandboxed code runs, plus the habit of fixing the working directory first so generated files land in the right place.

    7.7k GitHub stars~1.1k tokensUpdated 1 mo ago
    Auto-check passed
  • Fallback workflow for executing Python code when executecodesandbox fails repeatedly

    7.7k GitHub stars~1.1k tokensUpdated 1 mo ago
    Auto-check passed

Works with

Questions about Document Python Direct Exec

What does Document Python Direct Exec do?

Use direct Python execution for reliable spreadsheet and document/PDF generation operations. Document Python Direct Exec is an agent skill from HKUDS/OpenSpace.

When should I use Document Python Direct Exec?

Document Python Direct Exec fits situations like: tasks that involve Excel spreadsheets; tasks that involve PDF.

How do I install Document Python Direct Exec in Claude Code?

Run `npx skills add HKUDS/OpenSpace --skill document-python-direct-exec -a claude-code`. Or copy the skill folder (benchmarks/gdpval/skills/spreadsheet-direct-python-merged-343937 in HKUDS/OpenSpace) into .claude/skills/document-python-direct-exec in your project. Claude Code loads it when a task matches its description.

How do I install Document Python Direct Exec in Codex?

Run `npx skills add HKUDS/OpenSpace --skill document-python-direct-exec -a codex`. Or copy the skill folder (benchmarks/gdpval/skills/spreadsheet-direct-python-merged-343937 in HKUDS/OpenSpace) into .agents/skills/document-python-direct-exec in your project. Codex loads it when a task matches its description.

Can I use Document Python Direct Exec in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add HKUDS/OpenSpace --skill document-python-direct-exec -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/document-python-direct-exec, .gemini/skills/document-python-direct-exec, .github/skills/document-python-direct-exec and .opencode/skills/document-python-direct-exec in your project.

What does Document Python Direct Exec need to run?

Going by SKILL.md and its folder, Document Python Direct Exec needs the command-line tools its instructions call (python3 and pip). Our summary lists: Python 3.

Does Document Python Direct Exec access the network?

SKILL.md contains no URLs. Its commands use pip, which can reach the network depending on how they are called. This is read from the text; nothing was executed.

Is Document Python Direct Exec safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Document Python Direct Exec use?

Document Python Direct Exec is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Document Python Direct Exec use?

About 2.9k tokens (SKILL.md is roughly 12k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Document Python Direct Exec?

Skills that share tags, products or a category with Document Python Direct Exec: Instrument Data To Allotrope (aws-samples/amazon-bedrock-agents-healthcare-lifesciences, 274 stars), Doc Cleaner (notoriouslab/doc-cleaner, 309 stars), Mineru (Nebutra/MinerU-Skill, 122 stars) and Office To Md (shuyu-labs/WebCode, 278 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Document Python Direct Exec?

HKUDS (a GitHub organization) maintains it in HKUDS/OpenSpace, which has 7,743 GitHub stars. The repository holds 199 skills in this directory. The repository was last updated on August 12, 2026.

Source: HKUDS/OpenSpace on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.