본문으로 건너뛰기
Skillpedia
자동화6.6k · #13869

n8n-code-python

하는 일

이 스킬은 n8n 2.x용 Code 노드 안에 Python 코드를 작성하는 방법을 설명합니다. JavaScript 대신 Python을 원하거나, 오래된 템플릿에서 복사한 코드를 고치는 사람을 위한 스킬입니다.

사용하는 경우

  • ✓n8n Code 노드에서 특별히 Python을 원할 때.
  • ✓오래된 n8n 템플릿의 Python 코드가 n8n 2.x로 바뀐 후 NameError로 깨질 때.
  • ✓Python Code 노드가 보안 위반, 차단된 import, 없는 내장 함수를 보고할 때.

스킬 링크

https://github.com/czlonkowski/n8n-skills/blob/main/skills/n8n-code-python/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/czlonkowski/n8n-skills/blob/main/skills/n8n-code-python/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“내 n8n Python Code 노드에서 _input 관련 NameError가 나요. 새 버전에 맞게 어떻게 고치나요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

n8n 2.x의 Python은 기본 도우미가 줄어든 채 네이티브로 실행되며, 사용할 새 변수를 보여 주고, 표준 라이브러리 import는 기본으로 차단된다고 설명합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Python Code Node (native)

Since n8n 2.0 the Code node's Python runs as native Python in a task runner (language: "pythonNative"). The old Pyodide "Python (Beta)" is gone, and with it every n8n helper it had: _input, _json, _node, _now, _today and _jmespath all raise NameError now. Code copied from old templates, forum posts or older docs usually breaks on this.


JavaScript first — stronger than before

Native Python gives you two variables and plain Python, and by default no imports: no json, datetime or re. Everything n8n-specific ($('Node'), $jmespath, Luxon, this.helpers.httpRequest, static data) exists only in JavaScript. Use Python only when the user explicitly asks for it. Even then, first check whether an expression, Edit Fields, or a native node (Crypto, Date & Time, HTML, XML) does the job. See n8n-code-javascript and the transform gatekeeper in n8n-expression-syntax.


Quick start

# Run Once for All Items (default mode)
return [
    {"json": {"name": it["json"]["name"], "revenue": it["json"]["revenue"]}}
    for it in _items
    if it["json"].get("active")
]
# Run Once for Each Item
row = _item["json"]
return {"json": {**row, "name_upper": (row.get("name") or "").upper()}}

Node config: {"language": "pythonNative", "mode": "runOnceForAllItems" | "runOnceForEachItem", "pythonCode": "..."} on n8n-nodes-base.code typeVersion 2.


The only inputs: _items and _item

Mode Variable Shape
Run Once for All Items _items list of plain dicts {"json": {...}, "pairedItem": {...}}
Run Once for Each Item _item one plain dict {"json": {...}, "pairedItem": {...}}
  • Each variable exists only in its own mode. _items in each-item mode (or _item in all-items mode) raises NameError.
  • Dict access only. it["json"]["name"] or it["json"].get("name"). it.json.name raises AttributeError: 'dict' object has no attribute 'json'.
  • No other nodes. There is no _node / $('Node') equivalent. If you need data from another branch, bring it in with Merge first, or read it in JavaScript.
  • Webhook payloads are under ["body"]: _items[0]["json"].get("body", {}).get("email").
  • Binary data isn't covered here. Read and write binary in JavaScript (see n8n-binary-and-data).
  • pairedItem: returning _items / _item keeps it. When you build new dicts and downstream uses $('Node').item, add "pairedItem": {"item": i} to each returned item. That isn't verified on native Python yet, so test-run before relying on it.
  • Missing keys: prefer .get(key, default). row["missing"] raises KeyError.

Migration table for legacy code:

Legacy (Pyodide) Native
_input.all() _items
_input.first()["json"] _items[0]["json"] (guard if _items)
_input.item / _json _item / _item["json"]
_node["X"] not available: Merge upstream, or use JS
_now, _today not available: pass {{ $now.toISO() }} in via Edit Fields, or use JS
_jmespath(data, q) not available: $jmespath in an expression, or a comprehension
item.json.field item["json"]["field"]

Imports: blocked by default

Every import (standard library and third-party) is checked against an allowlist before the code runs. The default allowlist is empty, so even import json rejects the whole node:

Security violations detected
Line 1: Import of standard library module 'json' is disallowed. Allowed stdlib modules: none
  • n8n Cloud: no imports at all.
  • Self-hosted: the admin can allowlist modules in the task-runner config (see n8n-self-hosting → TASK_RUNNERS.md). Some instances therefore allow json, datetime and re, and most don't.
  • Default to import-free code. If an import would really help, confirm it first: a one-line test node import json + return [{"json": {"ok": True}}], or ask the user. Never assume.
  • Without imports: parse JSON strings upstream ({{ JSON.parse($json.payload) }} in Edit Fields). Do date math with the Date & Time node or Luxon in an expression. ISO-8601 strings still compare and sort correctly as plain strings. Use the Crypto node for hashing.
  • requests, pandas and numpy are never available unless the admin built a custom runner image. Use the HTTP Request node for HTTP.

Sandbox limits (these fail even without import

자주 묻는 질문

오래된 n8n Python 코드가 왜 실패하나요?

_input 같은 예전 도우미 변수는 n8n 2.x에 더 이상 없으므로, 코드를 업데이트해야 합니다.

Python 라이브러리를 가져올 수 있나요?

표준 라이브러리 import는 기본으로 꺼져 있으므로, 이 스킬은 코드를 어떻게 조정해야 하는지 설명합니다.

JavaScript 대신 Python을 골라야 하나요?

이 스킬은 JavaScript가 n8n 기능을 더 많이 갖고 있으므로, 명시적으로 원할 때만 Python을 쓰라고 말합니다.

상세 정보

작성자의 원본 설명

Write Python in n8n Code nodes (native Python, `language` pythonNative, n8n 2.x). Use when the user explicitly wants Python in a Code node, when migrating old Pyodide/"Python (Beta)" code that used _input/_json/_node/_now, or when a Python Code node fails with NameError, "Security violations detected", "Import of standard library module … is disallowed", "__build_class__ not found", "A 'json' property isn't a dictionary", or "Python runner unavailable". Covers the only two variables (_items/_item), dict-only access, imports blocked by default, the sandbox's denied builtins, accepted return sha

repo: czlonkowski/n8n-skills

인기도

GitHub 스타
6.6k
순위
#13869
라이선스
MIT
업데이트
2026. 10. 24.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬