# Python Script Runner: pip, Dataset Rows In & Out (`enisbodlli/python-script-runner`) Actor

Run your own Python code on Apify with pip packages. Send JSON or Dataset rows in, get rows out in a Dataset plus logs and errors. Callable from the API, n8n, Make, Zapier or AI agents.

- **URL**: https://apify.com/enisbodlli/python-script-runner.md
- **Developed by:** [Enis Bodlli](https://apify.com/enisbodlli) (community)
- **Categories:** Developer tools, Automation, Agents
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.50 / 1,000 code runs

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Python Script Runner: pip, Dataset Rows In & Out

Run **your own Python code** on Apify, with any **pip packages** you list. Send **JSON rows or an
Apify Dataset** in, and get **rows out** in a Dataset, with the logs, the error and its traceback in
one OUTPUT record. Call it from the Apify API, **n8n, Make, Zapier** or an **AI agent** whenever a
workflow needs a few lines of Python: clean a scraper's output, compute a field, reshape JSON, call
an API with your key, or build an Excel file with pandas.

- **Three ways to call your code.** `main(input, rows)` once for the whole batch, `main(row, input)`
  for each row with a per-row `_ok` and `_error`, or a plain script that calls `push()`.
- **pandas, numpy, requests, httpx, BeautifulSoup, lxml, openpyxl, dateutil and PyYAML preinstalled**,
  and anything else from PyPI through `requirements`.
- **$2 per 1,000 code runs** ($1.50 on Gold), with 20 GB-seconds of compute and 100 output rows
  included in each run. Input that is refused costs nothing.

The easiest way to try it: keep the example input and press **Start**. The example code marks which
of three products cost more than the median, and you get three rows in about 4 seconds.

### What you get

Each value your code returns or passes to `push()` becomes one Dataset row, with your own fields:

```json
[
    { "item": "apple", "price": 1.2, "aboveMedian": false },
    { "item": "bread", "price": 2.5, "aboveMedian": false },
    { "item": "cheese", "price": 6.9, "aboveMedian": true }
]
```

In per-row mode each row also says whether that row worked:

```json
[
    { "double": 4, "_index": 0, "_ok": true },
    { "_ok": false, "_error": "KeyError: 'value'", "_index": 1 },
    { "double": 8, "_index": 2, "_ok": true }
]
```

The run's key-value store holds `OUTPUT`: the status, stdout and stderr, the error type, message and
traceback, timings, the Python version, the packages installed and the row counts.

### What you can do with it

- **Post-process another Actor's results**: pass its Dataset ID, transform or filter the rows in
  pandas, and get a clean Dataset back.
- **Add a Python step to n8n, Make or Zapier** without hosting a server.
- **Give an AI agent a Python tool** through the Apify MCP server: it sends code and rows and reads
  back structured rows and errors.
- **Call an API with your own key**: put the key in `secrets`, read it with `os.environ`.

### How to use it

1. Write your code in **Code**. Define `def main(input, rows):` and return a list of dicts, a dict,
   or a pandas DataFrame. Or leave out `main` and call `push(row)` or `push(list_of_rows)` yourself.
2. Put your data in **Rows** (a JSON array of objects), or choose a **Dataset**, or both. The
   **Input** object is passed to `main` as `input` for settings such as thresholds or URLs.
3. Pick **Call mode**: `once`, `perRow` or `script`.
4. Add packages under **Requirements**, one PyPI specifier per line, such as `tabulate` or
   `rapidfuzz>=3`. Only package names, extras and version clauses are accepted.
5. Press **Start**, or call the Actor through the API and read the default Dataset.

In every mode the names `push`, `INPUT` and `ROWS` exist in your code's globals.

#### How long it takes

The example finishes in about 4 seconds on Apify. Installing a small package such as `tabulate`
adds 2 to 3 seconds; large packages add more and count towards the compute in the run.

### Pricing

Pay per event, with Bronze, Silver and Gold discounts:

| Event | Price | Silver | Gold |
|---|---|---|---|
| Code run (includes 20 GB-seconds and 100 rows) | $0.002 | $0.00176 | $0.0015 |
| Extra GB-minute, each one started past the included 20 GB-seconds | $0.01 | $0.0088 | $0.0075 |
| 100 extra output rows, each block started past the first 100 | $0.002 | $0.00176 | $0.0015 |
| Actor start (Apify's standard event, per GB of memory) | $0.00005 | | |

A GB-second is memory in GB times seconds: at the default 512 MB, a 40-second run is included.

Worked examples at the regular price:

- **1,000 runs** like the example (a few seconds, under 100 rows each) cost **$2.05**.
- One run that cleans **5,000 rows** in 10 seconds costs $0.002 + 49 x $0.002 = **$0.10**.
- One 3-minute pandas job at 2 GB is 360 GB-seconds: $0.002 + 6 x $0.01 = **$0.062**.

Your maximum charge per run is respected: once it is reached, the code is stopped, the rows already
stored stay, and OUTPUT says `charge-limit`. A run whose code raises an error still costs the code
run and the compute it used, because the code did run.

### Input

```json
{
    "code": "def main(input, rows):\n    import pandas as pd\n    df = pd.DataFrame(rows)\n    df['total'] = df['price'] * input['qty']\n    return df",
    "callMode": "once",
    "rows": [{ "item": "apple", "price": 1.2 }, { "item": "bread", "price": 2.5 }],
    "input": { "qty": 3 },
    "requirements": [],
    "timeoutSeconds": 120
}
```

| Field | What it does |
|---|---|
| `code` | Your Python code (required). |
| `callMode` | `once`, `perRow` or `script`. Default `once`. |
| `rows` | JSON objects passed in as rows. |
| `datasetId` | An Apify Dataset whose items are added after `rows`; `datasetOffset` skips the first ones. |
| `maxInputRows` | Most rows read in total. Default 10,000. |
| `input` | A JSON object passed to `main` as `input`. |
| `requirements` | PyPI packages to install for this run. |
| `secrets` | Encrypted environment variables, such as `{"MY_API_KEY": "..."}`. Their values are replaced by `***` in logs and errors. |
| `timeoutSeconds` | Time your code may run, up to 3,600 s. Default 120. |
| `installTimeoutSeconds` | Time pip may take. Default 180. |
| `maxOutputRows` | Most rows stored; the rest are counted as dropped. Default 10,000. |
| `maxLogKb` | Most stdout and stderr kept, each, as head and tail. Default 256 KB. |
| `failRunOnError` | Make the run fail when your code or the install fails. Default off: the run succeeds and OUTPUT holds the error, which suits workflows that branch on it. |
| `allowApifyApi` | Pass this run's Apify token to your code, for example to call other Actors. Default off. |

### Output

- **Default Dataset**: your rows, nothing added except `_index`, `_ok` and `_error` in per-row mode.
- **OUTPUT** in the default key-value store:

```json
{
    "status": "ok",
    "callMode": "once",
    "rowsIn": 3,
    "rowsOut": 3,
    "rowsDropped": 0,
    "perRowErrors": 0,
    "durationMs": 62,
    "installMs": 0,
    "packagesInstalled": [],
    "python": "3.11.2",
    "stdout": "",
    "stderr": "",
    "error": null
}
```

`status` is one of `ok`, `code-error`, `install-failed`, `timeout`, `charge-limit`,
`output-too-large` or `aborted`.

### Limits

- Python 3.11 on Debian. Packages that need system libraries not in the image may fail to install.
- Values that are not JSON become text; NaN and infinity become `null`. One row may be at most 9 MB
  (Apify's Dataset limit), and the stored output at most 200 MB per run.
- Rows are held in memory: for very large inputs raise the memory or use `datasetOffset` in batches.
- Your code runs in its own process inside this Actor's container. The Apify token is not in its
  environment unless you turn on `allowApifyApi`, but the container is not a security sandbox
  against your own code; run only code you trust.
- Network access is open, so your code can call APIs. What it fetches, and what you do with the
  data, is your responsibility under the sites' terms and the law.
- A run that is restarted keeps the rows already stored and is not charged twice for them. Code in
  `once` or `script` mode that was interrupted runs again from the start; `perRow` mode continues
  from the next row.

### FAQ

#### Is it safe to put API keys in the input?

Use the `secrets` field: Apify stores it encrypted, and the Actor replaces each secret value with
`***` in stdout, stderr and error messages. Do not print keys in a changed form (for example
base64), because only the exact values are masked.

#### Why did my run succeed when my code raised an error?

By default the error goes into OUTPUT so a workflow can read it and decide. Turn on
`failRunOnError` to make the run fail instead.

#### Which packages are already installed?

pandas, numpy, requests, httpx, beautifulsoup4, lxml, openpyxl, python-dateutil and PyYAML. Listing
them again in `requirements` is not needed.

#### Can I return a pandas DataFrame?

Yes. A DataFrame returned from `main` or passed to `push()` becomes one row per record.

#### Can an AI agent use it?

Yes. Through the Apify MCP server or the API, an agent sends `code` and `rows` and reads the Dataset
and OUTPUT, which carry structured errors instead of a free-text log.

#### Can I run it on a schedule or from n8n, Make or Zapier?

Yes. Any Apify integration can start it with JSON input and read the Dataset when the run finishes.

### More Actors from this developer

- [Podcast & Audio Transcriber](https://apify.com/enisbodlli/podcast-audio-transcriber): podcasts,
  MP3s and videos to text with Whisper, with timed segments and subtitles.
- [Video Frame Extractor](https://apify.com/enisbodlli/video-keyframe-extractor): frames, scene
  changes and contact sheets from videos.
- [ATS Job Postings: Workday, Greenhouse, Lever & Ashby](https://apify.com/enisbodlli/ats-job-postings):
  every open job of the companies you choose.
- [Website Contact Scraper](https://apify.com/enisbodlli/website-contact-scraper): emails, phones
  and social profiles from company websites.
- [Email Validator & List Cleaner](https://apify.com/enisbodlli/email-validator): syntax and domain
  checks for a mailing list.

# Actor input Schema

## `code` (type: `string`):

Your Python code. Define main or call push() directly.

## `callMode` (type: `string`):

once calls main(input, rows); perRow calls main(row, input); script executes the file.

## `rows` (type: `array`):

JSON object rows, before any Dataset rows.

## `datasetId` (type: `string`):

Optional Apify Dataset whose items are added to rows, for example the output of a scraper run.

## `datasetOffset` (type: `integer`):

First Dataset row to read.

## `maxInputRows` (type: `integer`):

Maximum combined JSON and Dataset rows.

## `installTimeoutSeconds` (type: `integer`):

Wall time allowed for pip installation.

## `timeoutSeconds` (type: `integer`):

Wall time allowed for your code, excluding pip.

## `maxOutputRows` (type: `integer`):

Maximum stored rows; further rows are counted and dropped.

## `maxLogKb` (type: `integer`):

Maximum captured stdout and stderr each, keeping head and tail.

## `input` (type: `object`):

Additional JSON object passed to your main function as input.

## `requirements` (type: `array`):

PyPI package specifiers only; for example requests\[socks]>=2.31,<3.

## `secrets` (type: `object`):

Encrypted environment variables, for example {"MY_API_KEY":"your-key"}. Values are redacted from logs.

## `failRunOnError` (type: `boolean`):

Fail the run for code or installation errors instead of reporting them in OUTPUT.

## `allowApifyApi` (type: `boolean`):

Pass this run's Apify API access to your code, for example to start other Actors. Off by default.

## Actor input object example

```json
{
  "code": "def main(input, rows):\n    import statistics\n    median = statistics.median(r[\"price\"] for r in rows)\n    return [{**r, \"aboveMedian\": r[\"price\"] > median} for r in rows]",
  "callMode": "once",
  "rows": [
    {
      "item": "apple",
      "price": 1.2
    },
    {
      "item": "bread",
      "price": 2.5
    },
    {
      "item": "cheese",
      "price": 6.9
    }
  ],
  "datasetId": "WkzbQMuFYuamGv3YF",
  "datasetOffset": 0,
  "maxInputRows": 10000,
  "installTimeoutSeconds": 180,
  "timeoutSeconds": 120,
  "maxOutputRows": 10000,
  "maxLogKb": 256,
  "input": {},
  "requirements": [],
  "secrets": {
    "MY_API_KEY": "your-key"
  },
  "failRunOnError": false,
  "allowApifyApi": false
}
```

# Actor output Schema

## `results` (type: `string`):

Your output JSON objects in the default Dataset.

## `summary` (type: `string`):

Status, logs, errors, timings, Python version, package specifiers and row counts.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "code": `def main(input, rows):
    import statistics
    median = statistics.median(r["price"] for r in rows)
    return [{**r, "aboveMedian": r["price"] > median} for r in rows]`,
    "callMode": "once",
    "rows": [
        {
            "item": "apple",
            "price": 1.2
        },
        {
            "item": "bread",
            "price": 2.5
        },
        {
            "item": "cheese",
            "price": 6.9
        }
    ],
    "datasetOffset": 0,
    "maxInputRows": 10000,
    "installTimeoutSeconds": 180,
    "timeoutSeconds": 120,
    "maxOutputRows": 10000,
    "maxLogKb": 256,
    "input": {},
    "requirements": [],
    "failRunOnError": false,
    "allowApifyApi": false
};

// Run the Actor and wait for it to finish
const run = await client.actor("enisbodlli/python-script-runner").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "code": """def main(input, rows):
    import statistics
    median = statistics.median(r[\"price\"] for r in rows)
    return [{**r, \"aboveMedian\": r[\"price\"] > median} for r in rows]""",
    "callMode": "once",
    "rows": [
        {
            "item": "apple",
            "price": 1.2,
        },
        {
            "item": "bread",
            "price": 2.5,
        },
        {
            "item": "cheese",
            "price": 6.9,
        },
    ],
    "datasetOffset": 0,
    "maxInputRows": 10000,
    "installTimeoutSeconds": 180,
    "timeoutSeconds": 120,
    "maxOutputRows": 10000,
    "maxLogKb": 256,
    "input": {},
    "requirements": [],
    "failRunOnError": False,
    "allowApifyApi": False,
}

# Run the Actor and wait for it to finish
run = client.actor("enisbodlli/python-script-runner").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "code": "def main(input, rows):\\n    import statistics\\n    median = statistics.median(r[\\"price\\"] for r in rows)\\n    return [{**r, \\"aboveMedian\\": r[\\"price\\"] > median} for r in rows]",
  "callMode": "once",
  "rows": [
    {
      "item": "apple",
      "price": 1.2
    },
    {
      "item": "bread",
      "price": 2.5
    },
    {
      "item": "cheese",
      "price": 6.9
    }
  ],
  "datasetOffset": 0,
  "maxInputRows": 10000,
  "installTimeoutSeconds": 180,
  "timeoutSeconds": 120,
  "maxOutputRows": 10000,
  "maxLogKb": 256,
  "input": {},
  "requirements": [],
  "failRunOnError": false,
  "allowApifyApi": false
}' |
apify call enisbodlli/python-script-runner --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,enisbodlli/python-script-runner"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/mpozIySdSG4YqwOIN/builds/Rofq9cA1WsynfsWIH/openapi.json
