> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sync.cdata.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python の記述

export const siteNameShortLower = "sync";

export const siteNameShort = "Sync";

export const siteName = "CData Sync";

After you complete the [prerequisites](./prerequisites), {siteName} can read and execute Python anywhere that APIScript can be written.

To instruct the {siteNameShort} scripting engine to use Python instead of APIScript, define Python as the scripting language by setting the language attribute on the `api:script` keyword, as shown below:

```xml theme={null}
<api:script language="python">
# Python code goes here
</api:script>
```

Python is embedded directly in the {siteNameShort} scripting engine, which allows users who are familiar with Python to use a similar syntax to interact with messages and context within their scripts.

You can also use APIScript and Python in the same script. This approach is useful when you already have APIScript in place but you need to implement additional logic using Python. Python can access items directly that are defined in APIScript, as shown in this example:

```xml theme={null}
<api:set attr="CustomerA.OrderID" value="123456" />
<api:script language="python">
print("The OrderId for CustomerA is", _ctx.CustomerA.OrderID)
</api:script>
```

Several Python methods and variables are designed to work specifically with the message, item, and attribute context in {siteNameShort}.

## Built-in Object Interfaces

The {siteNameShort} Python implementation provides two primary interfaces that expose the built-in variables listed below and enable access to scripting context.

* {siteNameShort}ScriptContext
* {siteNameShort}ScriptItem

### {siteNameShort}ScriptContext

This interface represents the primary scripting context for Python scripts in {siteNameShort}. It provides dictionary-like access to items and includes logging capabilities. The interface exposes the `_ctx` variable, which you use to access and manage the scripting context.

Available methods for this interface are as follows:

* `push`
* `log`

### {siteNameShort}ScriptItem

This interface represents individual data items in the {siteNameShort} scripting environment. It provides dictionary-like access to attributes and maintains lists of values for each item. The following variables are pre-instantiated {siteNameShort}ScriptItem objects that are available automatically :

* `_input`
* `output`

Available methods for this interface are as follows:

* `get`
* `clear`

### Understanding How {siteNameShort}ScriptContext and {siteNameShort}ScriptItem Work

The {siteNameShort}ScriptContext and {siteNameShort}ScriptItem interfaces work together to manage how data is accessed and processed within a script. The `_ctx` variable represents the overall scripting context and allows you to access or define items. You can use the syntax `_ctx.itemname` to create new items or access existing ones dynamically within the script.

The `_input` and `output` variables act as containers for data within the scripting context. The `_input` variable holds and exposes incoming data while the `output` variable holds and defines outgoing data.

Within this model, scripts typically read data from `_input`, use `_ctx` to access or organize items, and write results from `output`.

For more details, see [Built-in Variables](#built-in-object-interfaces) and [Operations](#operations).

## Built-in Variables

The built-in variables (`_ctx`, `_input`, and `output`) provide access to the core of the message context in a scripting environment. Use these variables to interact with the items that are available in the scripting engine.

### \_ctx

The `_ctx` variable is the primary way to access to the scripting environment. It provides access to all items that are available in the script and enables you to create new items, push items, and write entries to the application logs.

In the following example, the log method on the `_ctx` variable is used to write an entry to the application log at the INFO level:

```xml theme={null}
<api:script language="python">
...Python code...
_ctx.log('INFO', 'Successfully analyzed all data!')
... more Python code...
</api:script>
```

### \_input

The `_input` variable represents the read-only input item of the scripting engine. The available attributes vary based on the context in which you are writing your event. For example, in an event that executes after a job, the following inputs are available:

* `ConnectorId`
* `WorkspaceId`
* `MessageId`
* `FilePath`
* `FileName`
* `Attachment#`
* `Header:*`

However, if the event executes after an event, only outputs that are pushed from the previous events are available as inputs.

The following example prints the name of the connector to the log file of the current message:

```xml theme={null}
<api:script language="python">
...Python code...
print(_input.ConnectorId)
...more Python code...
</api:script>
```

This example takes the input file, renames it, logs the original name, and then pushes the same file with a new name:

```xml theme={null}
<api:script language="python">
originalname = _input.Filename
print("The original filename was ", originalname)
output.Filename = "mynewfile.xml"
output.Filepath = _input.Filepath
</api:script>
```

This example checks the name of the input file to determine whether it contains perishable or nonperishable items. Then, it sets a perishable header and value based on the file name:

```xml theme={null}
<api:script language="python">
# Check whether this is a perishable product list based on the filename
is_perishable = "perishables" in _input.FileName.lower()
# Set a perishable header and value based on the filename
output['Header:category'] = 'perishable' if is_perishable else 'non-perishable'
</api:script>
```

### output

The `output` variable is a built-in item that serves as an alternative to creating and pushing your own item when only a single output is needed. Unlike custom items that require you to explicitly call the `push()` method to send them as output, the `output` item is pushed automatically when the script completes. You just need to modify its properties and it is automatically pushed as output after the script execution is complete, without any additional `push()` calls needed.

You can set attributes directly on the item or define them by using a dictionary (`dict`), and you can do the same thing with items that you define yourself. The following example pushes an output file with some data:

```xml theme={null}
<api:script language="python">
output = {'data': 'This is a test',
          'filename': 'foo.txt'}
</api:script>
```

This next example takes the input file, renames it, logs the original name, then pushes the same file with a new name:

```xml theme={null}
<api:script language="python">
originalname = _input.Filename
print("The original filename was ", originalname)
output.Filename = "mynewfile.xml"
output.Filepath = _input.Filepath
</api:script>
```

## Operations

The following operations are available in the scripting environment to interact with the scripting context and items.

* `clear`
* `get`
* `log`
* `push`

These operations allow you to log information, manage item output, and access or modify item attributes.

### clear

The `clear()` operation clears the {siteNameShort}ScriptItem on which the method is called. The item remains the same, just empty.

```xml theme={null}
<api:script language="python">
product = _ctx.product
product.name = 'Milk'
product.price = '2.99'
product.tags = ['perishable', 'dairy', 'noreturn']
print("Before clear:", product)
# Use the clear() method to remove all items
product.clear()
print("After clear:", product)
</api:script>
```

The previous example produces the following output:

```xml theme={null}
Before clear: {"price":"2.99","name":"Milk","tags":["perishable","dairy","noreturn"]}
After clear: {}
```

### get

The `get(attr)` operation returns the value of the specified attribute on the {siteNameShort}ScriptItem. This operation provides a programmatic way to access item attributes by name. It is functionally equivalent to accessing the attribute directly using dot notation (for example, `_input.myattr`) or using dictionary-style access (for example, `_input.get('myattr')`).

The following example prints the value list of the `tags` attribute on the `item` object to the log file of the current script:

```xml theme={null}
<api:script language="python">
item = _ctx.item
item.name = 'Milk'
item.price = '2.99'
item.tags = ['perishable', 'dairy', 'noreturn']
print(item.get('tags'))
</api:script>
```

### log

The `log(level, message)` operation, available on the `_ctx` variable, allows you to write entries directly to the {siteNameShort} application log. The available log levels are DEBUG, INFO, WARNING and ERROR.

The following example uses the Python logging context to record an error-level message when data evaluation fails for a specific connector:

```xml theme={null}
<api:script language="python">
...Python code...
_ctx.log('ERROR', f'Data evaluation failed in connector {_input.ConnectorId}!')
...more Python code...
</api:script>
```

### push

The `push(item)` operation pushes the supplied item as output of the script. If no item is specified, the current output item is pushed.

In the following example, a new item (`foo`) is created in the {siteNameShort}ScriptContext, assigned some data and a filename, and then pushed out.

```xml theme={null}
<api:script language="python">
foo = _ctx.foo
foo.Filename = "test2.txt"
foo.Data = "bar"
_ctx.push(foo)
</api:script>
```
