Python Script
The Python Script action step allows you to execute custom Python code with access to your process mining data. This provides maximum flexibility for data transformation, custom integrations, and specialized processing.
Overview
When you configure a Python Script action step, the system:
- Collects data from all your selected analyses
- Makes this data available to your Python code
- Executes your script in a secure environment
- Allows you to process, transform, or send data anywhere
This is the most powerful and flexible action step, suitable for advanced users who need custom functionality beyond the built-in options.
When to Use Python Script
Use Python Script when you need to:
- Send data to custom APIs or webhooks
- Transform data before exporting to other systems
- Integrate with databases or data warehouses
- Create custom file formats or reports
- Perform calculations not available in standard mindzieStudio features
- Integrate with third-party services (Slack, Teams, Salesforce, etc.)
Prerequisites
Before using Python Script:
- Basic Python programming knowledge is required
- Select analysis data in the Data step of the action wizard
- Understand the data structures available from your analyses
Configuration
To add a Python Script to your action, click the + button in the Action Steps section and select Python Script.
Script Editor
The Python Script dialog provides a code editor where you write your Python code. The script has access to:
- All data from your selected analyses
- Standard Python libraries
- Common data processing libraries (pandas, requests, etc.)
Available Data
Your script receives the selected analysis data in structured formats. You can access:
- Raw event log data
- Calculated metrics and statistics
- Analysis results and tables
- Visualization data
Example Scripts
Send Data to Webhook
import requests
import json
# Access the analysis data
data = get_analysis_data()
# Send to a webhook
response = requests.post(
'https://your-webhook-url.com/endpoint',
json=data,
headers={'Content-Type': 'application/json'}
)
if response.status_code == 200:
print("Data sent successfully")
else:
print(f"Error: {response.status_code}")
Export to Database
import pandas as pd
from sqlalchemy import create_engine
# Get analysis data as DataFrame
df = get_analysis_dataframe()
# Connect to database
engine = create_engine('postgresql://user:pass@host:5432/database')
# Write data to table
df.to_sql('process_metrics', engine, if_exists='replace', index=False)
print(f"Exported {len(df)} rows to database")
Send Slack Notification
import requests
# Get key metrics
metrics = get_analysis_data()
avg_duration = metrics['average_duration']
case_count = metrics['case_count']
# Send to Slack
slack_message = {
"text": f"Daily Process Summary: {case_count} cases processed, avg duration: {avg_duration}"
}
requests.post(
'https://hooks.slack.com/services/YOUR/WEBHOOK/URL',
json=slack_message
)
Custom CSV Export
import pandas as pd
from datetime import datetime
# Get data
df = get_analysis_dataframe()
# Transform data
df['export_date'] = datetime.now().strftime('%Y-%m-%d')
df['source'] = 'mindzieStudio'
# Save to custom location
filename = f"process_export_{datetime.now().strftime('%Y%m%d')}.csv"
df.to_csv(f'/exports/{filename}', index=False)
print(f"Exported to {filename}")
Best Practices
Test scripts manually first: Develop and test your Python code before scheduling it in an action. Use Python notebooks to verify logic.
Handle errors gracefully: Include try/except blocks to catch and log errors. Failed scripts should provide useful error messages.
Log important steps: Use print statements to track execution progress. These appear in the action history.
Keep credentials secure: Don't hardcode passwords or API keys in scripts. Use environment variables or secure storage.
Consider execution time: Actions have timeout limits. Optimize scripts for efficiency, especially with large datasets.
Validate data before processing: Check that expected data exists before attempting to use it. Handle missing data gracefully.
Common Patterns
Error Handling
try:
data = get_analysis_data()
process_data(data)
print("Success")
except Exception as e:
print(f"Error: {str(e)}")
# Optionally send alert
send_error_notification(str(e))
Data Validation
data = get_analysis_data()
if not data or len(data) == 0:
print("No data available - skipping export")
exit()
if 'required_column' not in data.columns:
print("Missing required column")
exit()
# Continue with processing
Conditional Processing
data = get_analysis_data()
# Only send alert if threshold exceeded
if data['average_duration'] > 24: # hours
send_alert("Process duration exceeds 24 hours!")
else:
print("Duration within acceptable range")
Troubleshooting
Script not executing
- Check action history for error messages
- Verify the action is enabled and scheduled
- Ensure Python syntax is correct
Data not available
- Confirm analyses are selected in the Data step
- Verify the analyses have been executed and contain data
- Check the data access methods in your script
Script timeout
- Optimize code for performance
- Process data in smaller batches
- Consider moving heavy processing to external systems
External service errors
- Verify API endpoints and credentials
- Check network connectivity from the execution environment
- Add retry logic for transient failures
Import errors
- Verify required libraries are available
- Contact support if you need additional Python packages
Limitations
- Scripts execute in a sandboxed environment
- Some system-level operations are restricted
- External network access may be limited by security policies
- Execution time is limited to prevent runaway scripts
Related Documentation
Support
If you encounter issues with Python Scripts:
- Email: support@mindzie.com
- Include your script code (with sensitive data removed)
- Note any error messages from the action history
- Describe the expected vs. actual behavior