The mechanical.py module#
Summary#
Connects to a gRPC Mechanical server and allows commands to be passed. |
Initialize the logger for the given mechanical instance. |
|
Decorate a function to suppress the logging for a Mechanical instance. |
|
Check whether a port is in use at the given host. |
|
Check the state of ports in a port range. |
|
Close all Mechanical instances within a port range. |
|
Create the |
|
Get path. |
|
Change to see if the default Mechanical path is valid. |
|
Change default path. |
|
Save path. |
|
Check if the |
|
Start Mechanical locally in gRPC mode. |
|
Start Mechanical locally in RPyC mode. |
|
Start Mechanical remotely using the Product Instance Management (PIM) API. |
|
Start Mechanical locally. |
|
Connect to an existing Mechanical server instance. |
Default message length. |
|
Default chunk size. |
|
Default file chunk size. |
|
Localhost address. |
|
Default Mechanical port. |
|
List of gallery instances. |
Description#
Connect to Mechanical gRPC server and issues commands.
Module detail#
- mechanical.setup_logger(loglevel='INFO', log_file=True, mechanical_instance=None)#
Initialize the logger for the given mechanical instance.
- mechanical.suppress_logging(func)#
Decorate a function to suppress the logging for a Mechanical instance.
- mechanical.port_in_use(port, host=LOCALHOST)#
Check whether a port is in use at the given host.
You must actually bind the address. Just checking if you can create a socket is insufficient because it is possible to run into permission errors like:
An attempt was made to access a socket in a way forbidden by its access permissions.
- mechanical.check_ports(port_range, ip='localhost')#
Check the state of ports in a port range.
- mechanical.close_all_local_instances(port_range=None, use_thread=True, transport_mode=None, certs_dir=None)#
Close all Mechanical instances within a port range.
You can use this method when cleaning up from a failed pool or batch run.
- Parameters:
- port_range
list,optional List of a range of ports to use when cleaning up Mechanical. The default is
None, in which case the ports managed by PyMechanical are used.- use_threadbool,
optional Whether to use threads to close the Mechanical instances. The default is
True. So this call will return immediately.- transport_mode
str,optional Transport mode used by the instances to close. The default is
None, in which case the OS default is used (wnua on Windows, mtls on Linux). Options are"insecure","mtls", or"wnua".- certs_dir
str,optional when the transport_mode is
mtls, the certificate directory must be specified - The default isNone, which checks the environment variable, - then defaults tocerts.
- port_range
Examples
Close all Mechanical instances connected on local ports.
>>> import ansys.mechanical.core as pymechanical >>> pymechanical.close_all_local_instances()
With specific security mode and certificate directory. >>> import ansys.mechanical.core as pymechanical >>> pymechanical.close_all_local_instances(transport_mode=”mtls”, certs_dir=”my_certs”)
- mechanical.create_ip_file(ip, path)#
Create the
mylocal.ipfile needed to change the IP address of the gRPC server.
- mechanical.get_mechanical_path(allow_input=True)#
Get path.
Deprecated - use ansys.tools.common.path.get_mechanical_path instead
- mechanical.check_valid_mechanical()#
Change to see if the default Mechanical path is valid.
- mechanical.change_default_mechanical_path(exe_loc)#
Change default path.
Deprecated - use ansys.tools.common.path.change_default_mechanical_path instead.
- mechanical.save_mechanical_path(exe_loc=None)#
Save path.
Deprecated - use ansys.tools.common.path.save_mechanical_path instead.
- mechanical.get_start_instance(start_instance_default=True)#
Check if the
PYMECHANICAL_START_INSTANCEenvironment variable exists and is valid.- Parameters:
- start_instance_defaultbool,
optional Value to return when
PYMECHANICAL_START_INSTANCEis unset.
- start_instance_defaultbool,
- Returns:
- bool
Truewhen thePYMECHANICAL_START_INSTANCEenvironment variable exists and is valid,Falsewhen this environment variable does not exist or is not valid. If it is unset,start_instance_defaultis returned.
- Raises:
OSErrorRaised when
PYMECHANICAL_START_INSTANCEis not eitherTrueorFalse(case independent).
- mechanical.launch_grpc(exec_file='', batch=True, port=MECHANICAL_DEFAULT_PORT, additional_switches=None, additional_envs=None, verbose=False, host='127.0.0.1', transport_mode=None, certs_dir='certs') int#
Start Mechanical locally in gRPC mode.
- Parameters:
- exec_file
str,optional Path for the Mechanical executable file. The default is
None, in which case the cached location is used.- batchbool,
optional Whether to launch Mechanical in batch mode. The default is
True. WhenFalse, Mechanical is launched in UI mode.- port
int,optional Port to launch the Mechanical instance on. The default is
MECHANICAL_DEFAULT_PORT. The final port is the first port available after (or including) this port.- additional_switches
list,optional List of additional arguments to pass. The default is
None.- additional_envs
dictionary,optional Dictionary of additional environment variables to pass. The default is
None.- verbosebool,
optional Whether to print all output when launching and running Mechanical. The default is
False. Printing all output is not recommended unless you are debugging the startup of Mechanical.- host: string, optional
Default is
127.0.0.1.- transport_mode
str,optional Use the transport mode to connect. The default is
wnuaon Windows andmtlson Linux. -insecureuse the insecure mode. -mtlsuse the mtls mode. -wnuause the windows named security mode - only valid on windows.- certs_dir
str,optional - when the transport_mode is
mtls, the certificate directory must be specified The default is
None, which checks the environment variable,then defaults to
certs.this directory should have
client.cert,client.keyandca.certfiles
- when the transport_mode is
- exec_file
- Returns:
intPort number that the Mechanical instance started on.
Notes
If
PYMECHANICAL_START_INSTANCEis set to FALSE, thelaunch_mechanicalmethod looks for an existing instance of Mechanical atPYMECHANICAL_IPon portPYMECHANICAL_PORT, with default to127.0.0.1and10000if unset. This is typically used for automated documentation and testing.Examples
Launch Mechanical using the default configuration.
>>> from ansys.mechanical.core import launch_mechanical >>> mechanical = launch_mechanical()
Launch Mechanical using a specified executable file.
>>> exec_file_path = "C:/Program Files/ANSYS Inc/v261/aisol/bin/win64/AnsysWBU.exe" >>> mechanical = launch_mechanical(exec_file=exec_file_path)
- mechanical.launch_rpyc(exec_file='', batch=True, port=MECHANICAL_DEFAULT_PORT, additional_switches=None, additional_envs=None, verbose=False) tuple[int, subprocess.Popen]#
Start Mechanical locally in RPyC mode.
- mechanical.launch_remote_mechanical(version=None, grpc_options=None) tuple[grpc.Channel, Any | None]#
Start Mechanical remotely using the Product Instance Management (PIM) API.
When calling this method, you must ensure that you are in an environment where PyPIM is configured. You can use the
pypim.is_configuredmethod to verify that PyPIM is configured.- Parameters:
- version
str,optional Mechanical version to run in the three-digit format. For example,
"261"to run 2026 R1. The default isNone, in which case the server runs the latest installed version.- grpc_options
listoftuple,optional Additional gRPC channel options to pass when creating the channel. For example:
[("grpc.default_authority", "localhost")]. The default isNone.
- version
- Returns:
Tuplecontainingchannel, remote_instance.
- mechanical.launch_mechanical(allow_input=True, exec_file=None, batch=True, loglevel='ERROR', log_file=False, log_mechanical=None, additional_switches=None, additional_envs=None, start_timeout=120, port=None, ip=None, host=None, start_instance=None, verbose_mechanical=False, clear_on_connect=False, cleanup_on_exit=True, version=None, keep_connection_alive=True, backend='mechanical', transport_mode=None, certs_dir=None, grpc_options=None, start_license=None, read_only=False) Mechanical#
Start Mechanical locally.
- Parameters:
- allow_input: bool, optional
Whether to allow user input when discovering the path to the Mechanical executable file.
- exec_file
str,optional Path for the Mechanical executable file. The default is
None, in which case the cached location is used. If PyPIM is configured and this parameter is set toNone, PyPIM launches Mechanical using itsversionparameter.- batchbool,
optional Whether to launch Mechanical in batch mode. The default is
True. WhenFalse, Mechanical launches in UI mode.- loglevel
str,optional Level of messages to print to the console. Options are:
"WARNING": Prints only Ansys warning messages."ERROR": Prints only Ansys error messages."INFO": Prints all Ansys messages.
The default is
WARNING.- log_filebool,
optional Whether to copy the messages to a file named
logs.log, which is located where the Python script is executed. The default isFalse.- log_mechanical
str,optional Path to the output file on the local disk to write every script command to. The default is
None. However, you might set"log_mechanical='pymechanical_log.txt'"to write all commands that are sent to Mechanical via PyMechanical to this file. You can then use these commands to run a script within Mechanical without PyMechanical.- additional_switches
list,optional Additional switches for Mechanical. The default is
None.- additional_envs
dictionary,optional Dictionary of additional environment variables to pass. The default is
None.- start_timeout
float,optional Maximum allowable time in seconds to connect to the Mechanical server. The default is
120.- port
int,optional Port to launch the Mechanical gRPC server on. The default is
None, in which case10000is used. The final port is the first port available after (or including) this port. You can override the default behavior of this parameter with thePYMECHANICAL_PORT=environment variable.PORT> - ip
str,optional IP address to use only when
start_instanceisFalse. The default isNone, in which case"127.0.0.1"is used. If you provide an IP address,start_instanceis set toFalse. A host name can be provided as an alternative to an IP address.- host
str,optional Alias for
ipparameter. Host address for the Mechanical gRPC server. If bothipandhostare provided,hosttakes precedence.- start_instancebool,
optional Whether to launch and connect to a new Mechanical instance. The default is
None, in which case an attempt is made to connect to an existing Mechanical instance at the givenipandportparameters, which have defaults of"127.0.0.1"and10000respectively. WhenTrue, a local instance of Mechanical is launched. You can override the default behavior of this parameter with thePYMECHANICAL_START_INSTANCE=FALSEenvironment variable.- verbose_mechanicalbool,
optional Whether to enable printing of all output when launching and running a Mechanical instance. The default is
False. This parameter should be set toTruefor debugging only as output can be tracked within PyMechanical.- clear_on_connectbool,
optional When
start_instanceisFalse, whether to clear the environment when connecting to Mechanical. The default isFalse. WhenTrue,a fresh environment is provided when you connect to Mechanical.
- cleanup_on_exitbool,
optional Whether to exit Mechanical when Python exits. The default is
True. WhenFalse, Mechanical is not exited when the garbage for this Mechanical instance is collected.- version
str,optional Mechanical version to run in the three-digit format. For example,
"261"for 2026 R1. The default isNone, in which case the server runs the latest installed version. If PyPIM is configured andexec_file=None, PyPIM launches Mechanical using itsversionparameter.- keep_connection_alivebool,
optional Whether to keep the gRPC connection alive by running a background thread and making dummy calls for remote connections. The default is
True.- backend
str,optional Type of RPC to use. The default is
"mechanical"which uses grpc. The other option is"python"which uses RPyC.- start_license
str,optional License type to use when starting Mechanical. The default is
None. When provided, the-pargument is passed to Mechanical. Common values include"mech_1","mech_2"etc. This parameter is only used whenstart_instanceisTrue.- read_onlybool,
optional Whether to start Mechanical in read-only mode. The default is
False.
- Returns:
ansys.mechanical.core.mechanical.MechanicalInstance of Mechanical.
Notes
If the environment is configured to use PyPIM and
start_instance=True, then starting the instance is delegated to PyPIM. In this case, most of the preceding parameters are ignored because the server-side configuration is used.Examples
Launch Mechanical.
>>> from ansys.mechanical.core import launch_mechanical >>> mech = launch_mechanical()
Launch Mechanical using a specified executable file.
>>> exec_file_path = "C:/Program Files/ANSYS Inc/v261/aisol/bin/win64/AnsysWBU.exe" >>> mech = launch_mechanical(exec_file=exec_file_path)
Connect to an existing Mechanical instance at IP address
192.168.1.30on port50001.>>> mech = launch_mechanical(start_instance=False, ip="192.168.1.30", port=50001)
Launch Mechanical with a specific license type.
>>> mech = launch_mechanical(start_license="mech_1")
- mechanical.connect_to_mechanical(ip=None, port=None, loglevel='ERROR', log_file=False, log_mechanical=None, connect_timeout=120, clear_on_connect=False, cleanup_on_exit=False, keep_connection_alive=True, transport_mode=None, certs_dir=None, grpc_options=None) Mechanical#
Connect to an existing Mechanical server instance.
- Parameters:
- ip
str,optional IP address for connecting to an existing Mechanical instance. The IP address defaults to
"127.0.0.1".- port
int,optional Port to listen on for an existing Mechanical instance. The default is
None, in which case10000is used. You can override the default behavior of this parameter with thePYMECHANICAL_PORT=environment variable.PORT> - loglevel
str,optional Level of messages to print to the console. Options are:
"WARNING": Prints only Ansys warning messages."ERROR": Prints only Ansys error messages."INFO": Prints all Ansys messages.
The default is
WARNING.- log_filebool,
optional Whether to copy the messages to a file named
logs.log, which is located where the Python script is executed. The default isFalse.- log_mechanical
str,optional Path to the output file on the local disk to write every script command to. The default is
None. However, you might set"log_mechanical='pymechanical_log.txt'"to write all commands that are sent to Mechanical via PyMechanical to this file. You can then use these commands to run a script within Mechanical without PyMechanical.- connect_timeout
float,optional Maximum allowable time in seconds to connect to the Mechanical server. The default is
120.- clear_on_connectbool,
optional Whether to clear the Mechanical instance when connecting. The default is
False. WhenTrue, a fresh environment is provided when you connect to Mechanical.- cleanup_on_exitbool,
optional Whether to exit Mechanical when Python exits. The default is
False. WhenFalse, Mechanical is not exited when the garbage for this Mechanical instance is collected.- keep_connection_alivebool,
optional Whether to keep the gRPC connection alive by running a background thread and making dummy calls for remote connections. The default is
True.- transport_mode
str,optional Use the transport mode to connect. The default is
wnuaon Windows andmtlson Linux. -insecureuse the insecure mode. -mtlsuse the mtls mode. -wnuause the windows named security mode - only valid on windows.- certs_dir
str,optional when the transport_mode is
mtls, the certificate directory must be specified - The default isNone, which checks the environment variable, - then defaults tocerts. - this directory should haveclient.cert,client.keyandca.certfiles- grpc_options
listoftuple,optional Additional gRPC channel options to pass when creating the channel. For example:
[("grpc.default_authority", "localhost")]. See gRPC documentation for available options. The default isNone.
- ip
- Returns:
ansys.mechanical.core.mechanical.MechanicalInstance of Mechanical.
Examples
Connect to an existing Mechanical instance at IP address
192.168.1.30on port50001..>>> from ansys.mechanical.core import connect_to_mechanical >>> pymech = connect_to_mechanical(ip="192.168.1.30", port=50001)
- mechanical.MAX_MESSAGE_LENGTH#
Default message length.
- mechanical.DEFAULT_CHUNK_SIZE = 262144#
Default chunk size.
- mechanical.DEFAULT_FILE_CHUNK_SIZE = 1048576#
Default file chunk size.
- mechanical.LOCALHOST = '127.0.0.1'#
Localhost address.
- mechanical.MECHANICAL_DEFAULT_PORT = 10000#
Default Mechanical port.
- mechanical.client_to_server_loglevel#