Skip to content

Commit 5470c6e

Browse files
FEAT: Record console setups into a python file (#6914)
Co-authored-by: pyansys-ci-bot <[email protected]>
1 parent 27714c1 commit 5470c6e

File tree

6 files changed

+675
-120
lines changed

6 files changed

+675
-120
lines changed

doc/changelog.d/6914.added.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Record console setups into a python file

src/ansys/aedt/core/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,9 @@ def custom_show_warning(message, category, filename, lineno, file=None, line=Non
105105
from ansys.aedt.core.generic.general_methods import inside_desktop_ironpython_console
106106
from ansys.aedt.core.generic.general_methods import is_linux
107107
from ansys.aedt.core.generic.general_methods import is_windows
108-
from ansys.aedt.core.generic.general_methods import online_help
109108
from ansys.aedt.core.generic.general_methods import pyaedt_function_handler
110109
from ansys.aedt.core.generic.numbers_utils import Quantity
110+
from ansys.aedt.core.help import online_help
111111
from ansys.aedt.core.hfss import Hfss
112112
from ansys.aedt.core.hfss3dlayout import Hfss3dLayout
113113
from ansys.aedt.core.icepak import Icepak

src/ansys/aedt/core/extensions/installer/console_setup.py

Lines changed: 68 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -34,39 +34,48 @@
3434
"""
3535

3636
import atexit
37-
import os
37+
from pathlib import Path
3838
import sys
39+
from IPython import get_ipython
40+
import tempfile
3941

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

44-
try:
46+
try: # pragma: no cover
4547
if version <= "2023.1":
4648
from pyaedt import Desktop
4749
from pyaedt.generic.general_methods import active_sessions
4850
from pyaedt.generic.general_methods import is_windows
4951
else:
52+
from ansys.aedt.core import *
53+
import ansys.aedt.core # noqa: F401
5054
from ansys.aedt.core import Desktop
5155
from ansys.aedt.core.generic.general_methods import active_sessions
5256
from ansys.aedt.core.generic.general_methods import is_windows
53-
except ImportError:
57+
from ansys.aedt.core.generic.file_utils import available_file_name
58+
59+
except ImportError: # pragma: no cover
5460
# Debug only purpose. If the tool is added to the ribbon from a GitHub clone, then a link
5561
# to PyAEDT is created in the personal library.
56-
console_setup_dir = os.path.dirname(__file__)
57-
if "PersonalLib" in console_setup_dir:
58-
sys.path.append(os.path.join(console_setup_dir, "../..", "..", ".."))
62+
console_setup_dir = Path(__file__).resolve().parent
63+
if "PersonalLib" in console_setup_dir.parts:
64+
sys.path.append(str(console_setup_dir / ".." / ".." / ".."))
5965
if version <= "2023.1":
6066
from pyaedt import Desktop
6167
from pyaedt.generic.general_methods import active_sessions
6268
from pyaedt.generic.general_methods import is_windows
6369
else:
70+
from ansys.aedt.core import * # noqa: F401
71+
import ansys.aedt.core # noqa: F401
6472
from ansys.aedt.core import Desktop
6573
from ansys.aedt.core.generic.general_methods import active_sessions
6674
from ansys.aedt.core.generic.general_methods import is_windows
75+
from ansys.aedt.core.generic.file_utils import available_file_name
6776

6877

69-
def release(d):
78+
def release(d): # pragma: no cover
7079
d.logger.info("Exiting the PyAEDT Console.")
7180

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

7988

8089
sessions = active_sessions(version=version, student_version=False)
81-
if aedt_process_id in sessions:
90+
if aedt_process_id in sessions: # pragma: no cover
8291
session_found = True
8392
if sessions[aedt_process_id] != -1:
8493
port = sessions[aedt_process_id]
85-
if not session_found:
94+
if not session_found: # pragma: no cover
8695
sessions = active_sessions(version=version, student_version=True)
8796
if aedt_process_id in sessions:
8897
session_found = True
@@ -91,7 +100,7 @@ def release(d):
91100
port = sessions[aedt_process_id]
92101

93102
error = False
94-
if port:
103+
if port: # pragma: no cover
95104
desktop = Desktop(
96105
version=version,
97106
port=port,
@@ -100,7 +109,7 @@ def release(d):
100109
close_on_exit=False,
101110
student_version=student_version,
102111
)
103-
elif is_windows:
112+
elif is_windows: # pragma: no cover
104113
desktop = Desktop(
105114
version=version,
106115
aedt_process_id=aedt_process_id,
@@ -109,26 +118,25 @@ def release(d):
109118
close_on_exit=False,
110119
student_version=student_version,
111120
)
112-
else:
121+
else: # pragma: no cover
113122
print("Error. AEDT should be started in gRPC mode in Linux to connect to PyAEDT")
114123
print("use ansysedt -grpcsrv portnumber command.")
115124
error = True
116-
if not error: # pragma: no cover
125+
126+
if not error: # pragma: no cover
117127
print(" ")
118128

119129
print("\033[92m****************************************************************")
120130
print(f"* ElectronicsDesktop {version} Process ID {aedt_process_id}")
121131
print(f"* CPython {sys.version.split(' ')[0]}")
122132
print("*---------------------------------------------------------------")
123-
print("* Example: \033[94m hfss = ansys.aedt.core.Hfss() \033[92m")
124-
print("* Example: \033[94m m2d = ansys.aedt.core.Maxwell2d() \033[92m")
133+
print("* Example: \033[94m hfss = Hfss() \033[92m")
134+
print("* Example: \033[94m m2d = Maxwell2d() \033[92m")
135+
print("* Desktop object is initialized: \033[94mdesktop.logger.info('Hello world')\033[92m")
125136
print("* \033[31mType exit() to close the console and release the desktop. \033[92m ")
126-
print("* desktop object is initialized and available. Example: ")
127-
print("* \033[94mdesktop.logger.info('Hello world')\033[92m")
128137
print("****************************************************************\033[0m")
129138
print(" ")
130-
print(" ")
131-
print(" ")
139+
132140
if is_windows:
133141
try:
134142
import win32api
@@ -156,3 +164,44 @@ def signal_handler(sig, frame):
156164
except ImportError:
157165
pass
158166
atexit.register(release, desktop)
167+
168+
if version > "2023.1": # pragma: no cover
169+
170+
log_file = Path(tempfile.gettempdir()) / "pyaedt_script.py"
171+
log_file = available_file_name(log_file)
172+
173+
with open(log_file, 'a', encoding='utf-8') as f:
174+
f.write("# PyAEDT script recorded from PyAEDT Console:\n\n")
175+
f.write("import ansys.aedt.core\n")
176+
f.write("from ansys.aedt.core import *\n")
177+
178+
def log_successful_command(result):
179+
"""
180+
IPython Hook: Executes after every command (cell).
181+
Logs the input command only if 'result.error_in_exec' is False (no exception).
182+
"""
183+
# Check for execution error
184+
if not result.error_in_exec:
185+
command = result.info.raw_cell.strip()
186+
187+
# Avoid logging empty lines, comments, or the hook code itself
188+
if command and not command.startswith('#') and "log_successful_command" not in command:
189+
try:
190+
# Append the successful command to the log file
191+
with open(log_file, 'a', encoding='utf-8') as f:
192+
f.write(command + "\n")
193+
except Exception as e:
194+
# Handle potential file writing errors
195+
print(f"ERROR: Failed to write to log file: {e}")
196+
197+
198+
# Register the Hook
199+
ip = get_ipython()
200+
if ip:
201+
# Register the function to run after every command execution
202+
ip.events.register('post_run_cell', log_successful_command)
203+
# Inform the user that logging is active
204+
print(f"Successful commands will be saved to: \033[94m'{log_file}'\033[92m")
205+
print(" ")
206+
print(" ")
207+
print(" ")

src/ansys/aedt/core/generic/general_methods.py

Lines changed: 0 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -1103,103 +1103,3 @@ def install_with_pip(package_name, package_path=None, upgrade=False, uninstall=F
11031103
subprocess.run(command, check=True) # nosec
11041104
except subprocess.CalledProcessError as e: # nosec
11051105
raise AEDTRuntimeError("An error occurred while installing with pip") from e
1106-
1107-
1108-
class Help(PyAedtBase): # pragma: no cover
1109-
def __init__(self):
1110-
self._base_path = "https://aedt.docs.pyansys.com/version/stable"
1111-
self.browser = "default"
1112-
1113-
def _launch_ur(self, url):
1114-
import webbrowser
1115-
1116-
if self.browser != "default":
1117-
webbrowser.get(self.browser).open_new_tab(url)
1118-
else:
1119-
webbrowser.open_new_tab(url)
1120-
1121-
def search(self, keywords, app_name=None, search_in_examples_only=False):
1122-
"""Search for one or more keywords.
1123-
1124-
Parameters
1125-
----------
1126-
keywords : str or list
1127-
app_name : str, optional
1128-
Name of a PyAEDT app. For example, ``"Hfss"``, ``"Circuit"``, ``"Icepak"``, or any other available app.
1129-
search_in_examples_only : bool, optional
1130-
Whether to search for the one or more keywords only in the PyAEDT examples.
1131-
The default is ``False``.
1132-
"""
1133-
if isinstance(keywords, str):
1134-
keywords = [keywords]
1135-
if search_in_examples_only:
1136-
keywords.append("This example")
1137-
if app_name:
1138-
keywords.append(app_name)
1139-
url = self._base_path + f"/search.html?q={'+'.join(keywords)}"
1140-
self._launch_ur(url)
1141-
1142-
def getting_started(self):
1143-
"""Open the PyAEDT User guide page."""
1144-
url = self._base_path + "/User_guide/index.html"
1145-
self._launch_ur(url)
1146-
1147-
def examples(self):
1148-
"""Open the PyAEDT Examples page."""
1149-
url = self._base_path + "/examples/index.html"
1150-
self._launch_ur(url)
1151-
1152-
def github(self):
1153-
"""Open the PyAEDT GitHub page."""
1154-
url = "https://github.com/ansys/pyaedt"
1155-
self._launch_ur(url)
1156-
1157-
def changelog(self, release=None):
1158-
"""Open the PyAEDT GitHub Changelog for a given release.
1159-
1160-
Parameters
1161-
----------
1162-
release : str, optional
1163-
Release to get the changelog for. For example, ``"0.6.70"``.
1164-
"""
1165-
if release is None:
1166-
from ansys.aedt.core import __version__ as release
1167-
url = "https://github.com/ansys/pyaedt/releases/tag/v" + release
1168-
self._launch_ur(url)
1169-
1170-
def issues(self):
1171-
"""Open the PyAEDT GitHub Issues page."""
1172-
url = "https://github.com/ansys/pyaedt/issues"
1173-
self._launch_ur(url)
1174-
1175-
def ansys_forum(self):
1176-
"""Open the PyAEDT GitHub Issues page."""
1177-
url = "https://discuss.ansys.com/discussions/tagged/pyaedt"
1178-
self._launch_ur(url)
1179-
1180-
def developer_forum(self):
1181-
"""Open the Discussions page on the Ansys Developer site."""
1182-
url = "https://developer.ansys.com/"
1183-
self._launch_ur(url)
1184-
1185-
1186-
# class Property(property):
1187-
#
1188-
# @pyaedt_function_handler()
1189-
# def getter(self, fget):
1190-
# """Property getter."""
1191-
# return self.__class__.__base__(fget, self.fset, self.fdel, self.__doc__)
1192-
#
1193-
# @pyaedt_function_handler()
1194-
# def setter(self, fset):
1195-
# """Property setter."""
1196-
# return self.__class__.__base__(self.fget, fset, self.fdel, self.__doc__)
1197-
#
1198-
# @pyaedt_function_handler()
1199-
# def deleter(self, fdel):
1200-
# """Property deleter."""
1201-
# return self.__class__.__base__(self.fget, self.fset, fdel, self.__doc__)
1202-
1203-
# property = Property
1204-
1205-
online_help = Help()

0 commit comments

Comments
 (0)