Test variable and function scope#

This example calls the run_python_script method and checks the variable and function scope between calls.

Launch mechanical#

Launch a new Mechanical session in batch, setting the cleanup_on_exit argument to False. To close this Mechanical session when finished, this example must call the mechanical.exit() method.

from ansys.mechanical.core import launch_mechanical

mechanical = launch_mechanical(batch=True, cleanup_on_exit=False)
print(mechanical)
Ansys Mechanical [Ansys Mechanical Enterprise]
Product Version:241
Software build date: 11/27/2023 10:24:20

Run script to set variable#

Run the script to assign a value to a variable.

output = mechanical.run_python_script(
    """
x = 10
x
"""
)
print(f"x = {output}")
x = 10

Access the variable in the next call#

Run the script to change the variable value.

output = mechanical.run_python_script(
    """
x = x * 2
x
"""
)
print(f"x = {output}")
x = 20

Define function#

Run the script to define a function and access the variable defined in the previous call.

output = mechanical.run_python_script(
    """
def multiply_by_10():
    return x*10

multiply_by_10()
"""
)
print(f"output = {output}")
output = 200

Access the function#

Run the script to access the function defined in the previous call.

output = mechanical.run_python_script(
    """
multiply_by_10() * 2
"""
)
print(f"output = {output}")
output = 400

Close mechanical#

Close the mechanical instance.

mechanical.exit()

Total running time of the script: (0 minutes 0.181 seconds)

Gallery generated by Sphinx-Gallery