Mechanical#

class ansys.mechanical.core.mechanical.Mechanical(ip=None, port=None, timeout=60.0, loglevel='WARNING', log_file=False, log_mechanical=None, cleanup_on_exit=False, channel=None, remote_instance=None, keep_connection_alive=True, **kwargs)#

Bases: object

Connects to a gRPC Mechanical server and allows commands to be passed.

Overview#

get_product_info

Get product information by running a script on the Mechanical gRPC server.

launch

Launch Mechanical in batch or UI mode.

wait_till_mechanical_is_ready

Wait until Mechanical is ready.

run_python_script

Run a Python script block inside Mechanical.

run_python_script_from_file

Run the contents a python file inside Mechanical.

exit

Exit Mechanical.

upload

Upload a file to the Mechanical instance.

get_file_chunks

Construct the file upload request for the server.

list_files

List the files in the working directory of Mechanical.

download

Download files from the working directory of the Mechanical instance.

save_chunks_to_file

Save chunks to a local file.

download_project

Download all project files in the working directory of the Mechanical instance.

clear

Clear the database.

log_message

Log the message using the given log level.

log_debug

Log the debug message.

log_info

Log the info message.

log_warning

Log the warning message.

log_error

Log the error message.

verify_valid_connection

Verify whether the connection to Mechanical is valid.

log

Log associated with the current Mechanical instance.

version

Get the Mechanical version based on the instance.

name

Name (unique identifier) of the Mechanical instance.

busy

Return True when the Mechanical gRPC server is executing a command.

locked

Instance is in use within a pool.

is_alive

Whether there is an active connection to the Mechanical gRPC server.

project_directory

Get the project directory for the currently connected Mechanical instance.

exited

Whether Mechanical already exited.

set_log_level

Set the log level.

convert_to_server_log_level

Convert the log level to the server log level.

__del__

Clean up on exit.

__repr__

Get the user-readable string form of the Mechanical instance.

Import detail#

from ansys.mechanical.core.mechanical import Mechanical

Property detail#

property Mechanical.log#

Log associated with the current Mechanical instance.

property Mechanical.version: str#

Get the Mechanical version based on the instance.

Examples

Get the version of the connected Mechanical instance.

>>> mechanical.version
'242'
property Mechanical.name#

Name (unique identifier) of the Mechanical instance.

property Mechanical.busy#

Return True when the Mechanical gRPC server is executing a command.

property Mechanical.locked#

Instance is in use within a pool.

property Mechanical.is_alive: bool#

Whether there is an active connection to the Mechanical gRPC server.

property Mechanical.project_directory#

Get the project directory for the currently connected Mechanical instance.

Examples

Get the project directory of the connected Mechanical instance.

>>> mechanical.project_directory
'/tmp/ANSYS.username.1/AnsysMech3F97/Project_Mech_Files/'
property Mechanical.exited#

Whether Mechanical already exited.

Attribute detail#

Mechanical.ip_temp#

Method detail#

Mechanical.__del__()#

Clean up on exit.

static Mechanical.set_log_level(loglevel)#

Set the log level.

Parameters:
loglevelstr, int

Level of logging. Options are "DEBUG", "INFO", "WARNING" and "ERROR".

Examples

Set the log level to the "DEBUG" level.

# >>> mechanical.set_log_level(‘DEBUG’) # # Set the log level to info # # >>> mechanical.set_log_level(‘INFO’) # # Set the log level to warning # # >>> mechanical.set_log_level(‘WARNING’) # # Set the log level to error # # >>> mechanical.set_log_level(‘ERROR’)

Mechanical.get_product_info()#

Get product information by running a script on the Mechanical gRPC server.

Mechanical.__repr__()#

Get the user-readable string form of the Mechanical instance.

Mechanical.launch(cleanup_on_exit=True)#

Launch Mechanical in batch or UI mode.

Parameters:
cleanup_on_exitbool, optional

Whether to exit Mechanical when Python exits. The default is True. When False, Mechanical is not exited when the garbage for this Mechanical instance is collected.

Mechanical.wait_till_mechanical_is_ready(wait_time=-1)#

Wait until Mechanical is ready.

Parameters:
wait_timefloat, optional

Maximum allowable time in seconds for connecting to the Mechanical gRPC server.

static Mechanical.convert_to_server_log_level(log_level)#

Convert the log level to the server log level.

Parameters:
log_levelstr

Level of logging. Options are "DEBUG", "INFO", "WARNING", "ERROR", and "CRITICAL".

Returns:
Converted log level for the server.
Mechanical.run_python_script(script_block: str, enable_logging=False, log_level='WARNING', progress_interval=2000)#

Run a Python script block inside Mechanical.

It returns the string value of the last executed statement. If the value cannot be returned as a string, it will return an empty string.

Parameters:
script_blockstr

Script block (one or more lines) to run.

enable_logging: bool, optional

Whether to enable logging. The default is False.

log_level: str

Level of logging. The default is "WARNING". Options are "DEBUG", "INFO", "WARNING", and "ERROR".

progress_interval: int, optional

Frequency in milliseconds for getting log messages from the server. The default is 2000.

Returns:
str

Script result.

Examples

Return a value from a simple calculation.

>>> mechanical.run_python_script('2+3')
'5'

Return a string value from Project object.

>>> mechanical.run_python_script('ExtAPI.DataModel.Project.ProductVersion')
'2024 R2'

Return an empty string, when you try to return the Project object.

>>> mechanical.run_python_script('ExtAPI.DataModel.Project')
''

Return an empty string for assignments.

>>> mechanical.run_python_script('version = ExtAPI.DataModel.Project.ProductVersion')
''

Return value from the last executed statement from a variable.

>>> script='''
    addition = 2 + 3
    multiplication = 3 * 4
    multiplication
    '''
>>> mechanical.run_python_script(script)
'12'

Return value from last executed statement from a function call.

>>> script='''
    import math
    math.pow(2,3)
    '''
>>> mechanical.run_python_script(script)
'8'

Handle an error scenario.

>>> script = 'hello_world()'
>>> import grpc
>>> try:
        mechanical.run_python_script(script)
    except grpc.RpcError as error:
        print(error.details())
name 'hello_world' is not defined
Mechanical.run_python_script_from_file(file_path, enable_logging=False, log_level='WARNING', progress_interval=2000)#

Run the contents a python file inside Mechanical.

It returns the string value of the last executed statement. If the value cannot be returned as a string, it will return an empty string.

Parameters:
file_path

Path for the Python file.

enable_logging: bool, optional

Whether to enable logging. The default is False.

log_level: str

Level of logging. The default is "WARNING". Options are "DEBUG", "INFO", "WARNING", and "ERROR".

progress_interval: int, optional

Frequency in milliseconds for getting log messages from the server. The default is 2000.

Returns:
str

Script result.

Examples

Return a value from a simple calculation.

Contents of simple.py file

2+3

>>> mechanical.run_python_script_from_file('simple.py')
'5'

Return a value from a simple function call.

Contents of test.py file

import math

math.pow(2,3)

>>> mechanical.run_python_script_from_file('test.py')
'8'
Mechanical.exit(force=False)#

Exit Mechanical.

Parameters:
forcebool, optional

Whether to force Mechanical to exit. The default is False, in which case only Mechanical in UI mode asks for confirmation. This parameter overrides any environment variables that may inhibit exiting Mechanical.

Examples

Exit Mechanical.

>>> mechanical.Exit(force=True)
Mechanical.upload(file_name, file_location_destination=None, chunk_size=DEFAULT_FILE_CHUNK_SIZE, progress_bar=True)#

Upload a file to the Mechanical instance.

Parameters:
file_namestr

Local file to upload. Only the file name is needed if the file is relative to the current working directory. Otherwise, the full path is needed.

file_location_destinationstr, optional

File location on the Mechanical server to upload the file to. The default is None, in which case the project directory is used.

chunk_sizeint, optional

Chunk size in bytes. The default is 1048576.

progress_barbool, optional

Whether to show a progress bar using tqdm. The default is True. A progress bar is helpful for viewing upload progress.

Returns:
str

Base name of the uploaded file.

Examples

Upload the hsec.x_t file with the progress bar not shown.

>>> mechanical.upload('hsec.x_t', progress_bar=False)
Mechanical.get_file_chunks(file_location, file_name, chunk_size, progress_bar)#

Construct the file upload request for the server.

Parameters:
file_location_destinationstr, optional

Directory where the file to upload to the server is located.

file_namestr

Name of the file to upload.

chunk_sizeint

Chunk size in bytes.

progress_barbool

Whether to show a progress bar using tqdm.

Mechanical.list_files()#

List the files in the working directory of Mechanical.

Returns:
list

List of files in the working directory of Mechanical.

Examples

List the files in the working directory.

>>> files = mechanical.list_files()
>>> for file in files: print(file)
Mechanical.download(files, target_dir=None, chunk_size=DEFAULT_CHUNK_SIZE, progress_bar=None, recursive=False)#

Download files from the working directory of the Mechanical instance.

It downloads them from the working directory to the target directory. It returns the list of local file paths for the downloaded files.

Parameters:
filesstr, list[str], tuple(str)

One or more files on the Mechanical server to download. The files must be in the same directory as the Mechanical instance. You can use the Mechanical.list_files function to list current files. Alternatively, you can specify glob expressions to match file names. For example, you could use file* to match every file whose name starts with file.

target_dir: str

Default directory to copy the downloaded files to. The default is None and current working directory will be used as target directory.

chunk_sizeint, optional

Chunk size in bytes. The default is 262144. The value must be less than 4 MB.

progress_barbool, optional

Whether to show a progress bar using tqdm. The default is None, in which case a progress bar is shown. A progress bar is helpful for viewing download progress.

recursivebool, optional

Whether to use recursion when using a glob pattern search. The default is False.

Returns:
List[str]

List of local file paths.

Notes

There are some considerations to keep in mind when using the download() method:

  • The glob pattern search does not search recursively in remote instances.

  • In a remote instance, it is not possible to list or download files in a location other than the Mechanical working directory.

  • If you are connected to a local instance and provide a file path, downloading files from a different folder is allowed but is not recommended.

Examples

Download a single file.

>>> local_file_path_list = mechanical.download('file.out')

Download all files starting with file.

>>> local_file_path_list = mechanical.download('file*')

Download every file in the Mechanical working directory.

>>> local_file_path_list = mechanical.download('*.*')

Alternatively, the recommended method is to use the download_project() method to download all files.

>>> local_file_path_list = mechanical.download_project()
Mechanical.save_chunks_to_file(responses, filename, progress_bar=False, target_name='')#

Save chunks to a local file.

Parameters:
responses
filenamestr

Name of the local file to save chunks to.

progress_barbool, optional

Whether to show a progress bar using tqdm. The default is False.

target_namestr, optional

Name of the target file on the server. The default is "". The file must be in the same directory as the Mechanical instance. You can use the mechanical.list_files() function to list current files.

Returns:
file_sizeint

File size saved in bytes. If 0 is returned, no file was written.

Mechanical.download_project(extensions=None, target_dir=None, progress_bar=False)#

Download all project files in the working directory of the Mechanical instance.

It downloads them from the working directory to the target directory. It returns the list of local file paths for the downloaded files.

Parameters:
extensionslist[str], tuple[str], optional

List of extensions for filtering files before downloading them. The default is None.

target_dirstr, optional

Path for downloading the files to. The default is None.

progress_barbool, optional

Whether to show a progress bar using tqdm. The default is False. A progress bar is helpful for viewing download progress.

Returns:
List[str]

List of local file paths.

Examples

Download all the files in the project.

>>> local_file_path_list = mechanical.download_project()
Mechanical.clear()#

Clear the database.

Examples

Clear the database.

>>> mechanical.clear()
Mechanical.log_message(log_level, message)#

Log the message using the given log level.

Parameters:
log_level: str

Level of logging. Options are "DEBUG", "INFO", "WARNING", and "ERROR".

messagestr

Message to log.

Examples

Log a debug message.

>>> mechanical.log_message('DEBUG', 'debug message')

Log an info message.

>>> mechanical.log_message('INFO', 'info message')
Mechanical.log_debug(message)#

Log the debug message.

Mechanical.log_info(message)#

Log the info message.

Mechanical.log_warning(message)#

Log the warning message.

Mechanical.log_error(message)#

Log the error message.

Mechanical.verify_valid_connection()#

Verify whether the connection to Mechanical is valid.