Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/changelog.d/6914.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Record console setups into a python file
2 changes: 1 addition & 1 deletion src/ansys/aedt/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,9 @@ def custom_show_warning(message, category, filename, lineno, file=None, line=Non
from ansys.aedt.core.generic.general_methods import inside_desktop_ironpython_console
from ansys.aedt.core.generic.general_methods import is_linux
from ansys.aedt.core.generic.general_methods import is_windows
from ansys.aedt.core.generic.general_methods import online_help
from ansys.aedt.core.generic.general_methods import pyaedt_function_handler
from ansys.aedt.core.generic.numbers_utils import Quantity
from ansys.aedt.core.help import online_help
from ansys.aedt.core.hfss import Hfss
from ansys.aedt.core.hfss3dlayout import Hfss3dLayout
from ansys.aedt.core.icepak import Icepak
Expand Down
87 changes: 68 additions & 19 deletions src/ansys/aedt/core/extensions/installer/console_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,39 +34,48 @@
"""

import atexit
import os
from pathlib import Path
import sys
from IPython import get_ipython
import tempfile

aedt_process_id = int(sys.argv[1])
version = sys.argv[2]
print("Loading the PyAEDT Console.")

try:
try: # pragma: no cover
if version <= "2023.1":
from pyaedt import Desktop
from pyaedt.generic.general_methods import active_sessions
from pyaedt.generic.general_methods import is_windows
else:
from ansys.aedt.core import *
import ansys.aedt.core # noqa: F401
from ansys.aedt.core import Desktop
from ansys.aedt.core.generic.general_methods import active_sessions
from ansys.aedt.core.generic.general_methods import is_windows
except ImportError:
from ansys.aedt.core.generic.file_utils import available_file_name

except ImportError: # pragma: no cover
# Debug only purpose. If the tool is added to the ribbon from a GitHub clone, then a link
# to PyAEDT is created in the personal library.
console_setup_dir = os.path.dirname(__file__)
if "PersonalLib" in console_setup_dir:
sys.path.append(os.path.join(console_setup_dir, "../..", "..", ".."))
console_setup_dir = Path(__file__).resolve().parent
if "PersonalLib" in console_setup_dir.parts:
sys.path.append(str(console_setup_dir / ".." / ".." / ".."))
if version <= "2023.1":
from pyaedt import Desktop
from pyaedt.generic.general_methods import active_sessions
from pyaedt.generic.general_methods import is_windows
else:
from ansys.aedt.core import * # noqa: F401
import ansys.aedt.core # noqa: F401
from ansys.aedt.core import Desktop
from ansys.aedt.core.generic.general_methods import active_sessions
from ansys.aedt.core.generic.general_methods import is_windows
from ansys.aedt.core.generic.file_utils import available_file_name


def release(d):
def release(d): # pragma: no cover
d.logger.info("Exiting the PyAEDT Console.")

d.release_desktop(False, False)
Expand All @@ -78,11 +87,11 @@ def release(d):


sessions = active_sessions(version=version, student_version=False)
if aedt_process_id in sessions:
if aedt_process_id in sessions: # pragma: no cover
session_found = True
if sessions[aedt_process_id] != -1:
port = sessions[aedt_process_id]
if not session_found:
if not session_found: # pragma: no cover
sessions = active_sessions(version=version, student_version=True)
if aedt_process_id in sessions:
session_found = True
Expand All @@ -91,7 +100,7 @@ def release(d):
port = sessions[aedt_process_id]

error = False
if port:
if port: # pragma: no cover
desktop = Desktop(
version=version,
port=port,
Expand All @@ -100,7 +109,7 @@ def release(d):
close_on_exit=False,
student_version=student_version,
)
elif is_windows:
elif is_windows: # pragma: no cover
desktop = Desktop(
version=version,
aedt_process_id=aedt_process_id,
Expand All @@ -109,26 +118,25 @@ def release(d):
close_on_exit=False,
student_version=student_version,
)
else:
else: # pragma: no cover
print("Error. AEDT should be started in gRPC mode in Linux to connect to PyAEDT")
print("use ansysedt -grpcsrv portnumber command.")
error = True
if not error: # pragma: no cover

if not error: # pragma: no cover
print(" ")

print("\033[92m****************************************************************")
print(f"* ElectronicsDesktop {version} Process ID {aedt_process_id}")
print(f"* CPython {sys.version.split(' ')[0]}")
print("*---------------------------------------------------------------")
print("* Example: \033[94m hfss = ansys.aedt.core.Hfss() \033[92m")
print("* Example: \033[94m m2d = ansys.aedt.core.Maxwell2d() \033[92m")
print("* Example: \033[94m hfss = Hfss() \033[92m")
print("* Example: \033[94m m2d = Maxwell2d() \033[92m")
print("* Desktop object is initialized: \033[94mdesktop.logger.info('Hello world')\033[92m")
print("* \033[31mType exit() to close the console and release the desktop. \033[92m ")
print("* desktop object is initialized and available. Example: ")
print("* \033[94mdesktop.logger.info('Hello world')\033[92m")
print("****************************************************************\033[0m")
print(" ")
print(" ")
print(" ")

if is_windows:
try:
import win32api
Expand Down Expand Up @@ -156,3 +164,44 @@ def signal_handler(sig, frame):
except ImportError:
pass
atexit.register(release, desktop)

if version > "2023.1": # pragma: no cover

log_file = Path(tempfile.gettempdir()) / "pyaedt_script.py"
log_file = available_file_name(log_file)

with open(log_file, 'a', encoding='utf-8') as f:
f.write("# PyAEDT script recorded from PyAEDT Console:\n\n")
f.write("import ansys.aedt.core\n")
f.write("from ansys.aedt.core import *\n")

def log_successful_command(result):
"""
IPython Hook: Executes after every command (cell).
Logs the input command only if 'result.error_in_exec' is False (no exception).
"""
# Check for execution error
if not result.error_in_exec:
command = result.info.raw_cell.strip()

# Avoid logging empty lines, comments, or the hook code itself
if command and not command.startswith('#') and "log_successful_command" not in command:
try:
# Append the successful command to the log file
with open(log_file, 'a', encoding='utf-8') as f:
f.write(command + "\n")
except Exception as e:
# Handle potential file writing errors
print(f"ERROR: Failed to write to log file: {e}")


# Register the Hook
ip = get_ipython()
if ip:
# Register the function to run after every command execution
ip.events.register('post_run_cell', log_successful_command)
# Inform the user that logging is active
print(f"Successful commands will be saved to: \033[94m'{log_file}'\033[92m")
print(" ")
print(" ")
print(" ")
100 changes: 0 additions & 100 deletions src/ansys/aedt/core/generic/general_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -1103,103 +1103,3 @@ def install_with_pip(package_name, package_path=None, upgrade=False, uninstall=F
subprocess.run(command, check=True) # nosec
except subprocess.CalledProcessError as e: # nosec
raise AEDTRuntimeError("An error occurred while installing with pip") from e


class Help(PyAedtBase): # pragma: no cover
def __init__(self):
self._base_path = "https://aedt.docs.pyansys.com/version/stable"
self.browser = "default"

def _launch_ur(self, url):
import webbrowser

if self.browser != "default":
webbrowser.get(self.browser).open_new_tab(url)
else:
webbrowser.open_new_tab(url)

def search(self, keywords, app_name=None, search_in_examples_only=False):
"""Search for one or more keywords.

Parameters
----------
keywords : str or list
app_name : str, optional
Name of a PyAEDT app. For example, ``"Hfss"``, ``"Circuit"``, ``"Icepak"``, or any other available app.
search_in_examples_only : bool, optional
Whether to search for the one or more keywords only in the PyAEDT examples.
The default is ``False``.
"""
if isinstance(keywords, str):
keywords = [keywords]
if search_in_examples_only:
keywords.append("This example")
if app_name:
keywords.append(app_name)
url = self._base_path + f"/search.html?q={'+'.join(keywords)}"
self._launch_ur(url)

def getting_started(self):
"""Open the PyAEDT User guide page."""
url = self._base_path + "/User_guide/index.html"
self._launch_ur(url)

def examples(self):
"""Open the PyAEDT Examples page."""
url = self._base_path + "/examples/index.html"
self._launch_ur(url)

def github(self):
"""Open the PyAEDT GitHub page."""
url = "https://github.com/ansys/pyaedt"
self._launch_ur(url)

def changelog(self, release=None):
"""Open the PyAEDT GitHub Changelog for a given release.

Parameters
----------
release : str, optional
Release to get the changelog for. For example, ``"0.6.70"``.
"""
if release is None:
from ansys.aedt.core import __version__ as release
url = "https://github.com/ansys/pyaedt/releases/tag/v" + release
self._launch_ur(url)

def issues(self):
"""Open the PyAEDT GitHub Issues page."""
url = "https://github.com/ansys/pyaedt/issues"
self._launch_ur(url)

def ansys_forum(self):
"""Open the PyAEDT GitHub Issues page."""
url = "https://discuss.ansys.com/discussions/tagged/pyaedt"
self._launch_ur(url)

def developer_forum(self):
"""Open the Discussions page on the Ansys Developer site."""
url = "https://developer.ansys.com/"
self._launch_ur(url)


# class Property(property):
#
# @pyaedt_function_handler()
# def getter(self, fget):
# """Property getter."""
# return self.__class__.__base__(fget, self.fset, self.fdel, self.__doc__)
#
# @pyaedt_function_handler()
# def setter(self, fset):
# """Property setter."""
# return self.__class__.__base__(self.fget, fset, self.fdel, self.__doc__)
#
# @pyaedt_function_handler()
# def deleter(self, fdel):
# """Property deleter."""
# return self.__class__.__base__(self.fget, self.fset, fdel, self.__doc__)

# property = Property

online_help = Help()
Loading