### Basic Expression Language Examples Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/basic-python-troubleshooting/scripting-vs-sql-vs-expressions Examples of expression syntax used for calculations and conditional logic in Ignition. ```Expression =SUM(C5:C10) ``` ```Expression if({Root Container.type}="Type C",True,False) ``` -------------------------------- ### Instantiate PrettyPrinter and Make HTTP GET Request Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/web-services-suds-and-rest/http-methods Instantiates a PrettyPrinter for formatted output and makes a GET request to the OpenWeatherMap API. Requires an API key and includes parameters for latitude, longitude, and appid. The JSON response is then decoded into a Python dictionary. ```Python pp = pprint.PrettyPrinter(indent=4) url = "https://api.openweathermap.org/data/2.5/weather" myClient = system.net.httpClient() response = myClient.get(url, {"lat":38.652330, "lon":-121.189773, "appid":"Your API key"}) decodedDict = response.getJson() pp.pprint(decodedDict) ``` -------------------------------- ### Use Basic Arithmetic Operators Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/numeric-types Examples of common operators for addition and string concatenation. ```python 5 + 1 = 6 "Hello " + " World" ``` -------------------------------- ### Order of Operations Examples Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects Demonstrates how operator precedence affects the evaluation of expressions. ```python 6+10*2 # produces 6+(10*2) = 26 6*10+2 # produces (6*10)+2 = 62 10*6%2 # produces (10*6)%2 = 0 10%6*2 # produces (10%6)*2 = 8 ``` -------------------------------- ### Exporting Data to CSV Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-examples/exporting-and-importing-a-csv These examples demonstrate how to convert a component's dataset to a CSV string and write it to the local file system. ```python # Create a variable that references our Power Table. You could modify this part # of the example to point to a different component in the window. component = event.source.parent.getComponent('Power Table') # Use system.dataset.toCSV to turn the dataset into a CSV string csv = system.dataset.toCSV(component.data) # Write to local file system. Note the "r" character right before the directory path. # This denotes a raw string literal, meaning we ignore escape sequences (like the "/") system.file.writeFile(r"C:\myExports\myExport.csv", csv) ``` ```python # Create a variable that references our Power Table. You could modify this part # of the example to point to a different component in the window. component = event.source.parent.getComponent('Power Table') # Use system.dataset.toCSV to turn the dataset into a CSV string. csv = system.dataset.toCSV(component.data) # Use system.file.saveFile to have the user find a directory to write to. filePath = system.file.saveFile("myExport.csv", "csv", "Comma Separated Values") # We can check the value of filePath to make sure the user picked a path before # attempting to write. if filePath: system.file.writeFile(filePath, csv) ``` -------------------------------- ### Infinite While Loop Example Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/conditions-and-loops Demonstrates a common pitfall where a missing increment causes an infinite loop. ```python x = 0 while x < 10: x += 1 # Forgetting to add a way to increment "x" will cause an infinite loop print x ``` -------------------------------- ### Print 'Hello World' in Scripting Console Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/getting-started-with-scripting Use the Scripting Console for immediate feedback when testing or writing new scripts. This is a good starting point for learning Python in Ignition without needing to create UI components first. ```Python print 'Hello World' ``` -------------------------------- ### Example Tag Export with Alarms and OPC Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/json-format This JSON export demonstrates Tag configurations including alarm definitions and OPC item paths for atomic Tags. ```json { "tags": [ { "valueSource": "memory", "dataType": "Boolean", "alarms": [ { "setpointA": 1, "name": "Above Normal" } ], "name": "Boolean Tag", "value": false, "tagType": "AtomicTag" }, { "valueSource": "memory", "dataType": "Boolean", "name": "One Shot Trigger", "tagGroup": "Driven One Shot", "value": true, "tagType": "AtomicTag", "enabled": true }, { "valueSource": "opc", "opcItemPath": "ns\u003d1;s\u003d[Generic]_Meta:Random/RandomDouble1", "dataType": "Float8", "name": "Pressure3", "tagGroup": "Driven One Shot", "tagType": "AtomicTag", "enabled": true, "opcServer": "Ignition OPC UA Server" }, { "valueSource": "opc", "opcItemPath": "ns\u003d1;s\u003d[Generic]_Meta:Random/RandomDouble2", "dataType": "Float8", "name": "Thickness3", "tagGroup": "Driven One Shot", "tagType": "AtomicTag", "opcServer": "Ignition OPC UA Server" } ] } ``` -------------------------------- ### Instantiate SUDS Client and Print Methods Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/web-services-suds-and-rest/suds-library-overview Use this to get a reference to a SUDS client object and print all available methods, types, and information about the web service defined in the WSDL. This requires the suds.client module. ```python from suds.client import Client client = Client("http://www.w3schools.com/xml/tempconvert.asmx?WSDL") print client ``` -------------------------------- ### Iterate Tag Changes Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/gateway-event-scripts Example of checking specific change types within the event.changes set. ```python for i in event.changes: if i.toString() == "ValueChange" foo() ``` -------------------------------- ### PyRow index() Method Example Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/datasets Demonstrates using the index() method on a PyRow to find the first occurrence of an element. Includes error handling for when the element is not found. ```python for row in pyDataset: try: print row.index("Apple") except: print "No apples in this row" ``` -------------------------------- ### Define a JSON name/value pair Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/json-format A basic example of a single field name and its associated value. ```json { "companyName":"Inductive Automation" } ``` -------------------------------- ### Example Tag Export in JSON Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/json-format This JSON structure represents an exported Tag configuration, including UDT instances and their properties. ```json { "name": "Tank Instance", "typeId": "Tank UDT", "tagType": "UdtInstance", "tags": [ { "value": "80", "name": "Tank Level", "tagType": "AtomicTag" }, { "value": 80, "name": "sliderValue", "tagType": "AtomicTag" } ] } ``` -------------------------------- ### Execute SQL Query in Python Script Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/basic-python-troubleshooting/scripting-vs-sql-vs-expressions This example demonstrates calling a SQL query from a Python script using system.db.runPrepUpdate. It's recommended to test SQL queries in the Database Query Browser first. ```Python # Example of calling a SQL query in a script. # Line 5 creates a variable called "query", and assigns it a string consisting of a prepared statement (using SQL). # The query is then executed with the system.db.runPrepUpdate function. query = """ INSERT INTO my_table (col1, col2) VALUES (?, ?) """ # Example parameters params = ["value1", 123] # Execute the query system.db.runPrepUpdate(query, params) ``` -------------------------------- ### Importing Data from CSV Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-examples/exporting-and-importing-a-csv These examples show how to read CSV file contents into a string or iterate through rows using Python libraries. ```python # Ask the user to find the CSV in the local file system. path = system.file.openFile("csv") # Use readFileAsString to read the contents of the file as a string. # This string will be the parameter we pass to fromCSV below stringData = system.file.readFileAsString(path) # Split stringData into a List of strings, delimited by the new line character stringData = stringData.split("\n") # Iterate through the list, and do something with each line for i in range(len(stringData)): # We're printing the row here, but you could do something more useful with the data. print stringData[i] ``` ```python # Import Python's built-in csv library import csv # Ask the user to find the CSV in the local file system. path = system.file.openFile("csv") # Create a reader object that will iterate over the lines of a CSV. # We're using Python's built-in open() function to open the file. file = open(path) csvData = csv.reader(file) ``` -------------------------------- ### Make HTTP GET Request Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/web-services-suds-and-rest/http-methods Use system.net.httpClient() to fetch data from a specified URL with query parameters. Ensure you replace 'Your API key' with your actual API key. ```Python #Set the endpoint URL url = "https://api.openweathermap.org/data/2.5/weather" #Declare a variable for system function we are using myClient = system.net.httpClient() #Declare a variable and set the parameters for the endpoint URL #Instead of specifying the API call parameters for the endpoint URL in the beginning response = myClient.get(url, {"lat":38.652330, "lon":-121.189773, "appid":"Your API key"}) #Print the output print response.getText() ``` -------------------------------- ### Handle Division Errors Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/error-handling Examples of handling division by zero errors across different languages. ```python # We start with a value, which could represent some user input. x = 2 # We use that value in our try block, and have a simple print statement if there is an error. try: value = 100/x print value except: print "An error occurred!" ``` ```java // We start with a value, which could represent some user input. int x = 2; // We use that value in our try block, and have a simple print statement if there is an error. try { int value = 100/x; System.out.println(value); } catch (Exception e) { System.out.println("An error occurred!"); } ``` ```python # Import the Exception class import java.lang.Exception ``` -------------------------------- ### PyRow count() Method Example Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/datasets Demonstrates using the count() method on a PyRow to calculate the total occurrences of a given element within that row. ```python for row in pyDataset: print row.count("Apple") ``` -------------------------------- ### Use Keyword Arguments in Python Function Call Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/user-defined-functions Demonstrates calling a Python function using keyword arguments for improved readability and flexibility. This example shows how to specify an argument by its name ('max') rather than its position. ```Python print cap(150, max=200) ``` -------------------------------- ### Python If-Else Statement Example Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/conditions-and-loops Shows how to use an if-else statement to execute one block of code if a condition is true, and another block if it is false. ```python x = 15 if x < 10: print "x is less than 10" else: print "x is not less than 10" ``` -------------------------------- ### PyDataset Repeating Elements Example Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/datasets Shows how repeating elements in a PyDataset row can be manipulated, such as by multiplying the row to repeat its contents. ```python for row in PyDataset print row * 2 ``` -------------------------------- ### Python Simple If-Statement Example Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/conditions-and-loops Demonstrates a simple if statement where a condition is checked and a print statement executes if the condition is true. Another condition is checked and does not execute. ```python x = 5 z = 15 if x < 10: # Since the condition "x < 10" is true, # the following line will execute print "'x' is less than 10" if z < 10: # This condition "z < 10" is false, # so the following line will not execute print "this will never show" ``` -------------------------------- ### Initialize Power Table Component Reference (Python) Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/basic-python-troubleshooting/troubleshooting-workflow This line of code attempts to get a reference to a component named 'Power Table' within the parent container. If the component does not exist or is named differently, this will result in a NoneType object, leading to subsequent errors when accessing its properties. ```Python table = event.source.parent.getComponent('Power Table') ``` -------------------------------- ### Basic Python Exception Handling Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/error-handling A fundamental example of using a try-except block to catch general exceptions in Python. This is useful for catching any unexpected errors during script execution. ```python x = 2 try: value = 100/x print value except java.lang.Exception, e: print "An error occurred!" ``` -------------------------------- ### Python If-Elif-Else Statement Example Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/conditions-and-loops Demonstrates the use of elif and else to check multiple conditions sequentially. The first condition that evaluates to true will have its corresponding block executed. ```python x = 3 if x == 1: print "one" elif x == 2: print "two" elif x == 3: print "three" else: print "not 1-3" ``` -------------------------------- ### Generate Integer Ranges with Python's range() Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/built-in-functions Use the `range()` function to create lists of integers for iteration. Specify start, stop, and step values to control the sequence. ```Python print range(5) print range(1, 5) print range(1, 10, 3) print range(15, 0, -3) ``` -------------------------------- ### Get Power Table Cell Value and Write to Tag (Python) Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/basic-python-troubleshooting/troubleshooting-workflow This script retrieves the selected cell's value from a Power Table and writes it to a specified tag. Ensure the Power Table component name matches the one in the script ('Power Table' in this example) and the tag path is correct. ```Python # Create a variable that references the Power Table table = event.source.parent.getComponent('Power Table') # Find the cell the user currently has selected, and store the value in a variable userSelectedValue = table.data.getValueAt(table.selectedrow, table.selectedColumn) # Write the User Selected Value to a tag system.tag.write("Scripting/ButtonError/WriteTarget", userSelectedValue) ``` -------------------------------- ### Initialize SUDS Client and Print Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/web-services-suds-and-rest/suds-library-overview Instantiate a SUDS client by providing the WSDL URL and print the client object to inspect available services and types. ```python from suds.client import Client url = 'http://localhost:7575/webservices/hypothetical_webservice?wsdl' client = Client(url) print client ``` -------------------------------- ### Access Specific Data from JSON Response Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/web-services-suds-and-rest/http-methods Demonstrates how to access a specific value from a decoded JSON dictionary by navigating through its keys and list indices. This example retrieves the 'description' from the 'weather' list. ```Python print decodedDict.get("weather")[0].get("description") ``` -------------------------------- ### Initialize a Dictionary in Python Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects Shows the syntax for creating a dictionary using key-value pairs. ```python newDictionary = {"itemName":5} ``` -------------------------------- ### Slice Strings in Python Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/strings Extract parts of a string using slicing with start and end indices. The end index is not included in the slice. Default values can be used for start or end. ```Python a = "Inductive Automation" # Will print out 'ctive Auto'. Note how the space is counted as a character, # and the 14th location is before the m, which is not included. print a[4:14] ``` ```Python a = "Inductive Automation" # From index 0 to index 12. print a[:12] # Will print out: Inductive Au # From index 12 to the end of the string. print a[12:] # Will print out: tomation # From the 4th character from the end to the 5th index. Note this prints nothing because the start character is after the end character. print a[-4:5] # Will print out: # From the 8th character from the end to the 2nd character from the end. print a[-8:-2] # Will print out: tomati # From index 5 to the 5th character from the end. print a[5:-5] # Will print out: tive Autom ``` -------------------------------- ### Create a Python Dictionary Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/dictionaries Demonstrates how to create a basic Python dictionary with string keys and associated values. ```python # In this dictionary, I associated the name John Smith to the key "name", # and the id number 12345 to the key "id". myDictionary = {"name":"John Smith", "id":12345} ``` -------------------------------- ### Example of HTTP 401 Unauthorized Error Response Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/web-services-suds-and-rest/http-methods This is an example of the JSON response received when an HTTP request fails due to an invalid API key, resulting in a 401 Unauthorized status code. ```JSON {"cod":401, "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."} ``` -------------------------------- ### Initialize Lists and Tuples in Python Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects Shows the syntax for creating list and tuple sequence types. ```python newList = [1,2] newTuple = (2,5,7) ``` -------------------------------- ### Call a Project Library Script Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/project-library Invoke the hello function from the myFuncs module. ```python myFuncs.hello() ``` -------------------------------- ### Define Colors in Python Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects Illustrates setting colors using RGB tuples or the system.gui.color function. ```python label = event.source label.foreground = (255,0,0) #(red,green,blue) ``` ```python newColor = system.gui.color(255,0,0) ``` -------------------------------- ### Get Column Count Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/datasets Determine the total number of columns in a Dataset by calling `getColumnCount()`. ```Python print cities.getColumnCount() ``` -------------------------------- ### Open Windows Based on Client Location Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-examples/location-based-vision-startup-scripts Navigates to a specific window upon startup based on the client's hostname. Ensure that conflicting 'Open on Startup' window settings are disabled to avoid unexpected behavior. ```python # Open a window based on location # Grab the hostname that the user is logging in from hostname = system.tag.readBlocking(["[System]Client/Network/Hostname"])[0].value if hostname == "Machine A Computer": # If the user logs in on a computer that is called Machine A Computer, # then open the Machine A details window. system.nav.openWindow("Machine A Details") else: # Otherwise, open the overview system.nav.openWindow("Overview") ``` -------------------------------- ### Get All Column Types Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/datasets Retrieve a list of the data types for all columns in a Dataset by calling `getColumnTypes()`. ```Python print cities.getColumnTypes() ``` -------------------------------- ### Get All Column Names Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/datasets Obtain a list containing the names of all columns in a Dataset by calling `getColumnNames()`. ```Python print cities.getColumnNames() ``` -------------------------------- ### Get Dictionary Keys Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/dictionaries Retrieves a list of all keys present in a dictionary using the keys() method. ```python myDictionary = {"name":"John Smith", "id":12345} print myDictionary.keys() ``` -------------------------------- ### Create and Modify Dates with system.date Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/dates Use system.date.now or system.date.getDate to initialize dates, and system.date.setTime to adjust the time component. ```python # Get the current datetime. print system.date.now() # Create a date. The time will be set to midnight. newDate = system.date.getDate(2018, 10, 28) print newDate # Change the time on the new date to 11:30 am. print system.date.setTime(newDate, 11, 30, 0) ``` -------------------------------- ### Get Dictionary Length Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/dictionaries Uses the len() function to return the number of key-value pairs in a dictionary. ```python myDictionary = {"name":"John Smith", "id":12345} print len (myDictionary) ``` -------------------------------- ### Create a Dataset Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects Constructs a new dataset using a list of headers and a list of rows. ```python header = ["The Only Column"] rows = [[1],[2],[3]] myDataset = system.dataset.toDataSet(header, rows) ``` -------------------------------- ### Define a JSON object Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/json-format An example of a JSON object containing multiple properties within curly braces. ```json { "firstName":"Sally", "lastName":"Smith" } ``` -------------------------------- ### Get Row Count Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/datasets Find out the total number of rows present in a Dataset by using the `getRowCount()` method. ```Python print cities.getRowCount() ``` -------------------------------- ### Get Column Name by Index Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/datasets Retrieve the name of a column from a Dataset using its numerical index with `getColumnName()`. ```Python print cities.getColumnName(1) ``` -------------------------------- ### Accessing System Functions via Autocomplete Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/getting-started-with-scripting Demonstrates the initial syntax for accessing the system namespace in the script editor. ```python system. ``` -------------------------------- ### Define and Call a Simple Python Function Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/user-defined-functions Define a basic Python function that prints 'Hello World!' and then call it. This demonstrates the fundamental syntax for function definition and invocation. ```Python # First we define our function. def printHW(): print "Hello World!" # We can then call our function. printHW() ``` -------------------------------- ### Get Dictionary Values Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/dictionaries Retrieves a list of all values contained within a dictionary using the values() method. ```python myDictionary = {"name":"John Smith", "id":12345} print myDictionary.values() ``` -------------------------------- ### General SUDS Workflow Pseudocode Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/web-services-suds-and-rest/suds-library-overview This pseudocode outlines the general workflow for using the SUDS library: import the Client, instantiate it with a WSDL URL, and call desired methods via the service instance. ```pseudocode #Import the SUDS Client object from suds.client import Client #Instantiate a new Client Object client = Client("url_to_your_wsdl") #Call the desired method using the service instance variable client.service.MyMethod(myArgument) ``` -------------------------------- ### Get Column Type by Index Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/datasets Determine the data type of a specific column in a Dataset using its index with `getColumnType()`. ```Python print cities.getColumnType(3) ``` -------------------------------- ### Get Column Index by Name Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/datasets Find the numerical index of a column within a Dataset by providing its name to `getColumnIndex()`. ```Python print cities.getColumnIndex("Timezone") ``` -------------------------------- ### Log to Gateway System Logs in Perspective Session (Gateway Scope) Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/script-logging-print-statement-output Using `system.perspective.print` with a 'gateway' scope in a Perspective session directs the output to the Gateway system logs. ```python system.perspective.print(scope='gateway', msg="This logs to the Gateway system logs.") ``` -------------------------------- ### Get Current Datetime with Python datetime Library Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/dates Retrieves the current date and time using the datetime class. ```python import datetime # Returns the current datetime. print datetime.datetime.now() ``` ```python # Imports the class named 'datetime' from the 'datetime' library, so we don't have to state it twice. from datetime import datetime # Returns the current datetime. print datetime.now() ``` -------------------------------- ### Import Python Libraries Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/libraries Demonstrates importing entire libraries or specific functions to expand script functionality. ```python # This pseudo code will import a library, and then call a function of that library. import myLibrary myLibrary.specialFunction() ``` ```python # This pseudo code will import a function from a library, and then call that function. from myLibrary import specialFunction specialFunction() ``` -------------------------------- ### Define a JSON array of objects Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/json-format An example of a JSON array containing multiple objects, useful for structured lists of data. ```json { "companies":[ { "companyName":"Inductive Automation", "cityName":"Folsom", "stateName":"CA" }, { "companyName":"Hewlett Packard", "cityName":"Palo Alto", "stateName":"CA" }, { "companyName":"Apple", "cityName":"Cupertino", "stateName":"CA" } ] } ``` -------------------------------- ### Creating and Manipulating Tuples Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/lists-and-tuples Demonstrates tuple initialization, nesting, concatenation, and slicing operations. ```python # Tuples are very simple to create. myTuple = (1, 2, 3) print myTuple # Will print out: (1, 2, 3) # Empty tuples can also be created, to have items added to them later. myTuple = () # Like lists, tuples are not confined to hold values of a single data type either. myTuple = (1, "two", 3.3) # Tuples can even hold other tuples! myTuple = (1, ("two", 3.3), 4, 'five', (6, (7.7, 'eight'), 9)) a = (1, 2, 3) b = (4, 5, 6) # Combine two tuples to make a new tuple print a + b # Will print out: (1, 2, 3, 4, 5, 6) myTuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g') print myTuple[2:5] # Will print out: ('c', 'd', 'e') ``` -------------------------------- ### Execute For Loops Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting Demonstrates iterating over a collection using a for loop. ```python for item in myList: print item ``` -------------------------------- ### Create a Dataset in Python Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/datasets Use `system.dataset.toDataSet` to create a Dataset object from a list of headers and a list of data rows. Ensure each data row list matches the header list length. ```Python # First create a list that contains the headers, in this case there are 4 headers. headers = ["City", "Population", "Timezone", "GMTOffset"] # Then create an empty list, this will house our data. data = [] # Then add each row to the list. Note that each row is also a list object. data.append(["New York", 8363710, "EST", -5]) data.append(["Los Angeles", 3833995, "PST", -8]) data.append(["Chicago", 2853114, "CST", -6]) data.append(["Houston", 2242193, "CST", -6]) data.append(["Phoenix", 1567924, "MST", -7]) # Finally, both the headers and data lists are used in the function to create a Dataset object cities = system.dataset.toDataSet(headers, data) ``` -------------------------------- ### Declare and Assign Variables in Python Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects Demonstrates basic variable assignment and arithmetic operations. Spaces around the assignment operator are optional. ```python x=5 y=3 print x*y ``` ```python x = 5 y = 3 print x * y ``` -------------------------------- ### Python type() Function Example Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/built-in-functions Use type() to determine the data type of a variable. This is useful for debugging or conditional logic based on type. ```python var = 10 print type(var) print type(str(var)) ``` -------------------------------- ### Get Column Data as List Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/datasets Retrieve all values from a specific column in a Dataset as a Python list using `getColumnAsList`. Specify the column index. ```Python print cities.getColumnAsList(0) ``` -------------------------------- ### Populate and Add Contact via Web Service Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/web-services-suds-and-rest/suds-library-overview Create instances of complex types like 'Phone' and 'Name', populate their fields, assign them to a 'Contact' object, and then invoke the web service method 'addContact'. ```python contact = client.factory.create('Contact') phone= client.factory.create('Phone') phone.areacode = '916' phone.number = '5557777' name = client.factory.create('Name') name.first = 'John' name.last = 'Doe' contact.name = name contact.phone = phone contact.age = 30 client.service.addContact(contact) ``` -------------------------------- ### Iterate Through Dictionary Keys Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/dictionaries Illustrates how to use the keys() function to get a list of keys from a dictionary and iterate through them to access both keys and their corresponding values. ```python # The keys() function provides us with a list of keys, which we can iterate through and print out in addition to using in the value lookup. for key in myDict.keys(): print key, myDict[key] ``` -------------------------------- ### Implement If Statements Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting Illustrates the basic syntax for conditional execution using an if statement. ```python if condition == True: print value1 ``` -------------------------------- ### Python While-Loop Iterating Over a List Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/conditions-and-loops An example of a while loop that iterates through a list using an index and the len() function to determine the loop's termination condition. ```python listOfFruit = ['Apples', 'Oranges', 'Bananas'] x = 0 while x < len(listOfFruit): print listOfFruit[x] x = x + 1 ``` -------------------------------- ### Perform Arithmetic with Variables Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting Demonstrates dynamic variable assignment and basic multiplication in Python. ```python x=5 y=3 print x*y ``` -------------------------------- ### Python type() for String Validation Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/built-in-functions This example demonstrates validating a variable's type against the string type using the type() function for conditional execution. ```python # This example attempts to validate the type of a variable. As written, this will evaluate as True, and thus the print statement would execute. var = "My String" if type(var) == type(""): print "Variable 'var' is a string" ``` -------------------------------- ### Log to Wrapper Log in Perspective Designer Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/script-logging-print-statement-output In Perspective scripting within the Designer, a bare `print` statement will log to the `wrapper.log` files. ```python print "This logs to the wrapper.log." ``` -------------------------------- ### Log to Output Console in Perspective Designer Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/script-logging-print-statement-output For Perspective scripting in the Designer, `system.perspective.print` is recommended to log to the Designer's Output Console. ```python system.perspective.print("This logs to the Designer's Output Console.") ``` -------------------------------- ### Truncate Numbers with math.floor() Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/built-in-functions Use `math.floor()` to get the largest integer less than or equal to a given number. Remember to import the `math` module before use. ```Python import math var = 100.938 print math.floor(var) ``` -------------------------------- ### Log to Gateway and Wrapper Logs in Perspective Designer Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/script-logging-print-statement-output When scripting in Perspective within the Designer, `system.util.getLogger` logs to both the Gateway system logs and the `wrapper.log` files. ```python system.util.getLogger("MyLogger").info("This logs to Gateway system logs and wrapper.log.") ``` -------------------------------- ### Python isinstance() for String Validation Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/built-in-functions This example shows how to use the isinstance() function to check if a variable is of string type, offering a more direct approach than type() comparison. ```python # The isinstance() function can offer the same functionality as above. var = "My String" if isinstance(var, str): # Note the lack of quotation marks around the classinfo parameter. We want to reference the class str, not the string "str". print "Variable 'var' is a string" ``` -------------------------------- ### Python - Using print to Troubleshoot Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/basic-python-troubleshooting Use print statements to verify code behavior during script execution. Remember to remove or comment out these statements once troubleshooting is complete to avoid cluttering the console. ```Python myVar = system.tag.read("folder/tag") ``` -------------------------------- ### Read Tags with Scope Considerations Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-examples/reading-and-writing-to-tags Demonstrates reading tags with and without explicit Tag Providers. Specifying the provider is required for Shared scope scripts. ```python # Reading a Tag without the Tag Provider. You would not want to use this from the Shared scope. system.tag.readBlocking(["My/Tag/Path"]) # Reading from the same Tag, but specifying the Tag Provider. This format may be used safely in either scope. system.tag.readBlocking(["[default]My/Tag/Path"]) ``` -------------------------------- ### Python isinstance() Function Example Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/built-in-functions Use isinstance() to check if an object is an instance or subclass of a specified class. 'basestring' can be used to check for both string and unicode types. ```python var = 10 print isinstance(var,int)strVar = "string" print isinstance(strVar,basestring) ``` -------------------------------- ### Perform Addition and Subtraction with Numeric Types Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/numeric-types Demonstrates how Python handles type promotion when adding or subtracting integers and floats. ```python 4 + 5 # int + int = int 4.0 + 5 # float + int = float 4.0 + 5.3 # float + float = float ``` -------------------------------- ### Get Value by Row Index and Column Name Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/datasets Retrieve a specific value from a Dataset by providing the row index and the column name to `getValueAt(rowIndex, colName)`. ```Python print cities.getValueAt(2, "Population") ``` -------------------------------- ### Get Value by Row and Column Index Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/datasets Access a specific value within a Dataset using both the row and column numerical indexes with `getValueAt(rowIndex, colIndex)`. ```Python print cities.getValueAt(1, 2) ``` -------------------------------- ### Define a Project Library Script Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/project-library Create a function within a script module named myFuncs. ```python def hello(): return "Hi there!" ``` -------------------------------- ### Define a Function with Google-style Docstrings Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition Shows the required docstring format for enabling parameter completion and documentation hints in the Ignition script editor. ```python def setMode(mode): """Changes the mode of the running system Args: mode: An integer representing the mode to switch to. Returns: A boolean that indicates if the attempt at switching to the given mode was successful. Raises: Error: If communications are down, an exception will be thrown. """ # Function code goes here ``` -------------------------------- ### Print Hello World in Python Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/getting-started-with-scripting A simple print statement used for troubleshooting or testing scripts within the component scripting environment. ```python print "Hello World!" ``` -------------------------------- ### Create Specific Datetime Instances Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/dates Instantiates a datetime object by passing specific year, month, day, and time components. ```python from datetime import datetime # Prints out the following datetime: 2018-01-02 03:04:05.000006 print datetime(2018,1,2,3,4,5,6) ``` -------------------------------- ### Define a Gateway Scripting Project Function Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/project-library Create a function in a library called myFuncs within the designated Gateway Scripting Project. ```python def thankYou(user): system.gui.messageBox("Thanks for noticing me, " + user) ``` -------------------------------- ### Python For-Loop Using Range() Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/conditions-and-loops Demonstrates using the range() function within a for loop to repeat a task a specific number of times. The loop variable's value is not used in this example. ```python # Even though this example isn't using the value of "x", # the print statement will still be executed once for each item # in the list returned by range(). for x in range(4): print "this will print 4 times" ``` -------------------------------- ### Pseudocode Example: Missing Code Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/basic-python-troubleshooting/troubleshooting-nothing-happened This pseudocode illustrates a scenario where a critical line for modifying a variable is missing or commented out, preventing a condition from ever being met. Test such logic in the Script Console. ```pseudocode myVar = 0 def doSomething(): print "Doing work!" # We're not modifying the value of myVar directly after it is initialized, # so the current implementation of this code means the expression in our if-statement will never return True. # Perhaps doSomething() returns a value that needs to be assigned to myVar. if myVar == 10: doMoreStuff() ``` -------------------------------- ### Define and Pass Functions as Arguments Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/user-defined-functions Demonstrates defining a filter function and passing it as an argument to another function to process a list. ```python # We define a function that checks if the value passed in is even. def isEven(num): return num % 2 == 0 # We define a function that inserts our list into the appropriate function and returns valid values. def extract(filterFunction, list): newList = [] for entry in list: if filterFunction(entry): newList.append(entry) return newList # Prints out [0, 2, 4, 6, 8] # Notice that isEven as not invoked, but passed to the filter function. print extract(isEven, range(10)) ``` -------------------------------- ### Create Dates with Java Calendar Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects/dates Uses the java.util.Calendar class to instantiate a specific date. Note that months are zero-indexed, where January is 0. ```python from java.util import Calendar cal = Calendar.getInstance() # set year, month, day, hour, minute, second in one call # This sets it to Feb 25th, 1:05:00 PM, 2010 cal.set(2010, 1, 25, 13, 5, 0) myDate = cal.getTime() ``` -------------------------------- ### Show the Current Datetime Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/variables-datatypes-and-objects Retrieves the current system time and prints it using formatted output. ```python currentTime = system.date.now() print "The current time is: %s" % currentTime ``` -------------------------------- ### Pseudocode Example: Skipped Code Due to Incorrect Condition Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/basic-python-troubleshooting/troubleshooting-nothing-happened This pseudocode demonstrates how an incorrect operator in an if-statement (e.g., using '==' when '!=' was intended) can cause the code block to be skipped. Verify operators and indentation for correct script flow. ```pseudocode myVar = 0 if myVar == 10: print "Hello, the value of myVar matches the condition in the if-statement" ``` -------------------------------- ### Log to Client Console in Client Session Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/script-logging-print-statement-output From a Client session, `print` statements are displayed in the Console tab of the Help > Diagnostics popup window. ```python print "This logs to the Client's Help > Diagnostics Console." ``` -------------------------------- ### Extract Employee Details from XML String (Jython) Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-examples/parsing-xml-with-the-etree-library Iterate through an XML structure containing employee data to extract specific details like ID, name, and department. This example demonstrates accessing elements and attributes from a parsed XML string. ```Jython from javax.xml.parsers import DocumentBuilderFactory from java.io import ByteArrayInputStream # Define your XML string xmlString = """ John Doe Engineering Jane Smith Marketing """ # Replace with your actual XML string # Create a DOM document builder builderFactory = DocumentBuilderFactory.newInstance() builder = builderFactory.newDocumentBuilder() # Parse the XML string document = builder.parse(ByteArrayInputStream(xmlString.encode())) # Access the root element root = document.getDocumentElement() ``` -------------------------------- ### Parse XML Stream with StAX Parser in Python Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-examples/parsing-xml-with-the-etree-library This Python script uses the StAX parser to read an XML string sequentially. It initializes an XMLInputFactory and XMLStreamReader, then iterates through the stream, processing START_ELEMENT, END_ELEMENT, and CHARACTERS events. Attributes are also extracted when elements start. ```Python from javax.xml.stream import XMLInputFactory, XMLStreamReader from java.io import ByteArrayInputStream # Create an XML input factory inputFactory = XMLInputFactory.newInstance() # Create an XML stream reader streamReader = inputFactory.createXMLStreamReader(ByteArrayInputStream(xmlString.encode())) # Iterate through the XML stream while streamReader.hasNext(): event = streamReader.next() if event == XMLStreamReader.START_ELEMENT: print("Start Element:", streamReader.getLocalName()) # Print attributes, if any for i in range(streamReader.getAttributeCount()): print("Attribute:", streamReader.getAttributeLocalName(i), "=", streamReader.getAttributeValue(i)) elif event == XMLStreamReader.END_ELEMENT: print("End Element:", streamReader.getLocalName()) elif event == XMLStreamReader.CHARACTERS: print("Character Data:", streamReader.getText()) ``` -------------------------------- ### Read XML from File using DOM Parser (Jython) Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-examples/parsing-xml-with-the-etree-library Use this snippet to parse an XML file by its path. Ensure the XML file is located in the script's working directory. Requires `javax.xml.parsers` and `java.io` imports. ```Jython from javax.xml.parsers import DocumentBuilderFactory from java.io import File # Define your XML file path xmlFilePath = "file.xml" # Replace with your actual XML file path # Create a DOM document builder builderFactory = DocumentBuilderFactory.newInstance() builder = builderFactory.newDocumentBuilder() # Parse the XML file file = File(xmlFilePath) document = builder.parse(file) # Access the root element root = document.getDocumentElement() ``` -------------------------------- ### Python Pseudocode for For Loop Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/conditions-and-loops Outlines the syntax for a Python for loop, highlighting the use of the 'in' keyword and indentation for the loop body. ```python # In this example, "item" is a variable created specifically by the "for" loop to act as an iterator. # The name "item" is not a keyword, and a different variable name may be used. # Additionally, note that "for" and "in" are lowercase, and a colon is present at the end of the line. for item in sequence: # All statements that should execute each iteration must be indented after the "for" statement statement ``` -------------------------------- ### Define Python Function with Default Arguments Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/python-scripting/user-defined-functions Define a Python function 'cap' that accepts an argument 'x' and optional 'min' and 'max' arguments with default values. This function caps 'x' within the specified bounds. Examples show calling the function with and without providing 'min' and 'max'. ```Python # We first define our function. Notice that we have 3 different arguments. # x, min, and max. The min and the max are set to equal 0 and 100 respectively. def cap(x, min=0, max=100): # Check if x is less than the min, return the min if true. if x < min: return min # Check if x is greater than the max, return the max if true. elif x > max: return max # Return the value if it is within the bounds. else: return x # We can then see the outcome by running our function with a few different parameters. # This will print out a 40, since it is within the bounds. print cap(40) # This will print out "0", since it is less than the min of 0. print cap(-1) # This will print out "100", since it is greater than the max of 100. print cap(150) # This will print out "150", because it uses a max of 200 instead of the default 100. print cap(150, 0, 200) ``` -------------------------------- ### Log to Browser Console in Perspective Session (Client Scope) Source: https://www.docs.inductiveautomation.com/docs/8.1/platform/scripting/scripting-in-ignition/script-logging-print-statement-output When `system.perspective.print` is used with a 'client' scope in a Perspective session, the output is logged in the browser's developer console. ```python system.perspective.print(scope='client', msg="This logs to the browser console.") ```