Skip to content

Commit fe2302a

Browse files
committed
checking code style
1 parent f321bbb commit fe2302a

File tree

5 files changed

+36
-111
lines changed

5 files changed

+36
-111
lines changed

src/ansys/dyna/core/pre/__init__.py

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,13 @@
22
import logging
33
import os
44

5-
import appdirs
6-
75
from ansys.dyna.core.pre.dynalogging import Logger
86

97
LOG = Logger(level=logging.ERROR, to_file=False, to_stdout=True)
108
LOG.debug("Loaded logging module as LOG")
119

1210
_LOCAL_PORTS = []
1311

14-
try:
15-
import importlib.metadata as importlib_metadata
16-
except ModuleNotFoundError: # pragma: no cover
17-
import importlib_metadata
18-
19-
# __version__ = importlib_metadata.version(__name__.replace(".", "-"))
20-
2112
from .dynabase import *
2213
from .dynadem import DynaDEM
2314
from .dynaicfd import DynaICFD

src/ansys/dyna/core/pre/dynalogging.py

Lines changed: 14 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -35,16 +35,16 @@
3535
3636
.. code:: python
3737
38-
LOG.logger.setLevel('DEBUG')
39-
LOG.file_handler.setLevel('DEBUG') # If present.
40-
LOG.stdout_handler.setLevel('DEBUG') # If present.
38+
LOG.logger.setLevel("DEBUG")
39+
LOG.file_handler.setLevel("DEBUG") # If present.
40+
LOG.stdout_handler.setLevel("DEBUG") # If present.
4141
4242
4343
Alternatively:
4444
4545
.. code:: python
4646
47-
LOG.setLevel('DEBUG')
47+
LOG.setLevel("DEBUG")
4848
4949
This way ensures all the handlers are set to the input log level.
5050
@@ -54,7 +54,8 @@
5454
.. code:: python
5555
5656
import os
57-
file_path = os.path.join(os.getcwd(), 'pydyna.log')
57+
58+
file_path = os.path.join(os.getcwd(), "pydyna.log")
5859
LOG.log_to_file(file_path)
5960
6061
This sets the logger to be redirected also to that file. If you wish
@@ -64,15 +65,6 @@
6465
6566
To log using this logger, just call the desired method as a normal logger.
6667
67-
.. code:: python
68-
69-
>>> import logging
70-
>>> from ansys.dyna.core.pre.logging import Logger
71-
>>> LOG = Logger(level=logging.DEBUG, to_file=False, to_stdout=True)
72-
>>> LOG.debug('This is LOG debug message.')
73-
74-
DEBUG - - <ipython-input-24-80df150fe31f> - <module> - This is LOG debug message.
75-
7668
7769
Instance Logger
7870
~~~~~~~~~~~~~~~
@@ -89,17 +81,6 @@
8981
:func:`log_to_file() <PymapdlCustomAdapter.log_to_file>` or change the log level
9082
using :func:`logger.Logging.setLevel`.
9183
92-
You can use this logger like this:
93-
94-
.. code:: python
95-
>>> from ansys.dyna.core.pre import launch_mapdl
96-
>>> mapdl = launch_mapdl()
97-
>>> mapdl._log.info('This is a useful message')
98-
99-
INFO - GRPC_127.0.0.1:50056 - <ipython-input-19-f09bb2d8785c> - <module> - This is a useful message
100-
101-
102-
10384
Other loggers
10485
~~~~~~~~~~~~~
10586
You can create your own loggers using python ``logging`` library as
@@ -127,9 +108,7 @@
127108

128109
## Formatting
129110

130-
STDOUT_MSG_FORMAT = (
131-
"%(levelname)s - %(instance_name)s - %(module)s - %(funcName)s - %(message)s"
132-
)
111+
STDOUT_MSG_FORMAT = "%(levelname)s - %(instance_name)s - %(module)s - %(funcName)s - %(message)s"
133112

134113
FILE_MSG_FORMAT = STDOUT_MSG_FORMAT
135114

@@ -180,9 +159,7 @@ def __init__(self, logger, extra=None):
180159
def process(self, msg, kwargs):
181160
kwargs["extra"] = {}
182161
# This are the extra parameters sent to log
183-
kwargs["extra"][
184-
"instance_name"
185-
] = self.extra.name # here self.extra is the argument pass to the log records.
162+
kwargs["extra"]["instance_name"] = self.extra.name # here self.extra is the argument pass to the log records.
186163
return msg, kwargs
187164

188165
def log_to_file(self, filename=FILE_NAME, level=LOG_LEVEL):
@@ -196,9 +173,7 @@ def log_to_file(self, filename=FILE_NAME, level=LOG_LEVEL):
196173
Level of logging. E.x. 'DEBUG'. By default LOG_LEVEL
197174
"""
198175

199-
self.logger = addfile_handler(
200-
self.logger, filename=filename, level=level, write_headers=True
201-
)
176+
self.logger = addfile_handler(self.logger, filename=filename, level=level, write_headers=True)
202177
self.file_handler = self.logger.file_handler
203178

204179
def log_to_stdout(self, level=LOG_LEVEL):
@@ -320,9 +295,7 @@ class Logger:
320295
_level = logging.DEBUG
321296
_instances = {}
322297

323-
def __init__(
324-
self, level=logging.DEBUG, to_file=False, to_stdout=True, filename=FILE_NAME
325-
):
298+
def __init__(self, level=logging.DEBUG, to_file=False, to_stdout=True, filename=FILE_NAME):
326299
"""Customized logger class for PyDyna-Pre.
327300
328301
Parameters
@@ -471,13 +444,9 @@ def add_child_logger(self, sufix, level=None):
471444

472445
def _add_mapdl_instance_logger(self, name, mapdl_instance, level):
473446
if isinstance(name, str):
474-
instance_logger = PymapdlCustomAdapter(
475-
self._make_child_logger(name, level), mapdl_instance
476-
)
447+
instance_logger = PymapdlCustomAdapter(self._make_child_logger(name, level), mapdl_instance)
477448
elif not name: # pragma: no cover
478-
instance_logger = PymapdlCustomAdapter(
479-
self._make_child_logger("NO_NAMED_YET", level), mapdl_instance
480-
)
449+
instance_logger = PymapdlCustomAdapter(self._make_child_logger("NO_NAMED_YET", level), mapdl_instance)
481450
else:
482451
raise ValueError("You can only input 'str' classes to this method.")
483452

@@ -516,9 +485,7 @@ def add_instance_logger(self, name, mapdl_instance, level=None):
516485
count_ += 1
517486
new_name = name + "_" + str(count_)
518487

519-
self._instances[new_name] = self._add_mapdl_instance_logger(
520-
new_name, mapdl_instance, level
521-
)
488+
self._instances[new_name] = self._add_mapdl_instance_logger(new_name, mapdl_instance, level)
522489
return self._instances[new_name]
523490

524491
def __getitem__(self, key):
@@ -534,9 +501,7 @@ def handle_exception(exc_type, exc_value, exc_traceback):
534501
if issubclass(exc_type, KeyboardInterrupt):
535502
sys.__excepthook__(exc_type, exc_value, exc_traceback)
536503
return
537-
logger.critical(
538-
"Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback)
539-
)
504+
logger.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
540505

541506
sys.excepthook = handle_exception
542507

src/ansys/dyna/core/pre/errors.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
11
"""pydyna specific errors"""
22

3-
from functools import wraps
4-
5-
from grpc._channel import _InactiveRpcError, _MultiThreadedRendezvous
6-
7-
from ansys.dyna.core.pre import LOG as logger
83

94
SIGINT_TRACKER = []
105

@@ -51,4 +46,3 @@ class KwserverDidNotStart(RuntimeError):
5146

5247
def __init__(self, msg=""):
5348
RuntimeError.__init__(self, msg)
54-

src/ansys/dyna/core/pre/launcher.py

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,7 @@
66
import threading
77

88
from ansys.dyna.core.pre import LOG
9-
from ansys.dyna.core.pre.misc import (
10-
check_valid_ip,
11-
check_valid_port,
12-
)
9+
from ansys.dyna.core.pre.misc import check_valid_ip, check_valid_port
1310

1411
LOCALHOST = "127.0.0.1"
1512
DYNAPRE_DEFAULT_PORT = 50051
@@ -39,42 +36,38 @@ def port_in_use(port, host=LOCALHOST):
3936
return True
4037

4138

42-
def launch_grpc(
43-
port=DYNAPRE_DEFAULT_PORT,
44-
ip=LOCALHOST,
45-
server_path = None
46-
) -> tuple: # pragma: no cover
39+
def launch_grpc(port=DYNAPRE_DEFAULT_PORT, ip=LOCALHOST, server_path=None) -> tuple: # pragma: no cover
4740
"""Start kwserver locally in gRPC mode.
4841
Parameters
4942
----------
5043
port : int
5144
Port to launch PyDyna gRPC on. Final port will be the first
5245
port available after (or including) this port.
53-
46+
5447
Returns
5548
-------
5649
int
5750
Returns the port number that the gRPC instance started on.
5851
5952
"""
6053
LOG.debug("Starting 'launch_kwserver'.")
61-
54+
6255
command = "python kwserver.py"
6356
LOG.debug(f"Starting kwserver with command: {command}")
6457

65-
#env_vars = update_env_vars(add_env_vars, replace_env_vars)
58+
# env_vars = update_env_vars(add_env_vars, replace_env_vars)
6659
LOG.info(f"Running in {ip}:{port} the following command: '{command}'")
6760

6861
LOG.debug("kwserver starting in background.")
69-
process = subprocess.Popen(['python','kwserver.py'],cwd = server_path ,shell=True)
62+
process = subprocess.Popen(["python", "kwserver.py"], cwd=server_path, shell=True)
7063
process.wait()
7164
# while True:
7265
# pass
7366
return port
7467

7568

7669
class ServerThread(threading.Thread):
77-
def __init__(self,threadID,port,ip,server_path):
70+
def __init__(self, threadID, port, ip, server_path):
7871
threading.Thread.__init__(self)
7972
self.threadID = threadID
8073
self.port = port
@@ -83,7 +76,7 @@ def __init__(self,threadID,port,ip,server_path):
8376
self.process = None
8477

8578
def run(self):
86-
self.process = launch_grpc(ip=self.ip,port=self.port,server_path=self.server_path)
79+
self.process = launch_grpc(ip=self.ip, port=self.port, server_path=self.server_path)
8780

8881
def termination(self):
8982
self.process.termination()
@@ -97,7 +90,7 @@ def launch_dynapre(
9790
Parameters
9891
----------
9992
port : int
100-
Port to launch MAPDL gRPC on.
93+
Port to launch MAPDL gRPC on.
10194
ip : bool, optional
10295
Specify the IP address of the PyDyna instance to connect to.
10396
You can also provide a hostname as an alternative to an IP address.
@@ -115,7 +108,7 @@ def launch_dynapre(
115108
if (ip.lower() == "localhost" or ip == LOCALHOST) and not DynaSolution.grpc_local_server_on():
116109
LOG.debug("Starting kwserver")
117110
server_path = os.path.join(os.getcwd(), "../../src/ansys/dyna/core/pre/Server")
118-
threadserver = ServerThread(1,port=port,ip=ip,server_path=server_path)
111+
threadserver = ServerThread(1, port=port, ip=ip, server_path=server_path)
119112
threadserver.setDaemon(True)
120113
threadserver.start()
121114

@@ -126,9 +119,10 @@ def launch_dynapre(
126119

127120
# return dynasln
128121

122+
129123
if __name__ == "__main__":
130124
server_path = os.path.join(os.getcwd(), "Server")
131-
process = subprocess.Popen(['python','kwserver.py'],cwd = server_path ,shell=True)
125+
process = subprocess.Popen(["python", "kwserver.py"], cwd=server_path, shell=True)
132126
process.wait()
133127
process.terminate()
134-
print(process)
128+
print(process)

src/ansys/dyna/core/pre/misc.py

Lines changed: 9 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,16 @@
11
"""Module for miscellaneous functions and methods"""
2-
from functools import wraps
32
import inspect
43
import os
54
import random
65
import socket
76
import string
87
import sys
98
import tempfile
10-
from warnings import warn
11-
12-
from ansys.dyna.core.pre import LOG
139

1410
# path of this module
1511
MODULE_PATH = os.path.dirname(inspect.getfile(inspect.currentframe()))
1612

13+
1714
class Plain_Report:
1815
def __init__(self, core, optional=None, additional=None, **kwargs):
1916
"""
@@ -54,8 +51,8 @@ def __init__(self, core, optional=None, additional=None, **kwargs):
5451
except RuntimeError as e: # pragma: no cover
5552
self.kwargs["extra_meta"] = ("GPU Details", f"Error: {str(e)}")
5653
else:
57-
self.kwargs["extra_meta"] = ("GPU Details", "None")
58-
54+
self.kwargs["extra_meta"] = ("GPU Details", "None")
55+
5956
def get_version(self, package):
6057
try:
6158
import importlib.metadata as importlib_metadata
@@ -78,34 +75,20 @@ def __repr__(self):
7875
]
7976

8077
core = ["\nCore packages", "-------------"]
81-
core.extend(
82-
[
83-
f"{each.ljust(20)}: {self.get_version(each)}"
84-
for each in self.core
85-
if self.get_version(each)
86-
]
87-
)
78+
core.extend([f"{each.ljust(20)}: {self.get_version(each)}" for each in self.core if self.get_version(each)])
8879

8980
if self.optional:
9081
optional = ["\nOptional packages", "-----------------"]
9182
optional.extend(
92-
[
93-
f"{each.ljust(20)}: {self.get_version(each)}"
94-
for each in self.optional
95-
if self.get_version(each)
96-
]
83+
[f"{each.ljust(20)}: {self.get_version(each)}" for each in self.optional if self.get_version(each)]
9784
)
9885
else:
9986
optional = [""]
10087

10188
if self.additional:
10289
additional = ["\nAdditional packages", "-----------------"]
10390
additional.extend(
104-
[
105-
f"{each.ljust(20)}: {self.get_version(each)}"
106-
for each in self.additional
107-
if self.get_version(each)
108-
]
91+
[f"{each.ljust(20)}: {self.get_version(each)}" for each in self.additional if self.get_version(each)]
10992
)
11093
else:
11194
additional = [""]
@@ -126,6 +109,7 @@ def is_float(input_string):
126109
except ValueError:
127110
return False
128111

112+
129113
def random_string(stringLength=10, letters=string.ascii_lowercase):
130114
"""Generate a random string of fixed length"""
131115
return "".join(random.choice(letters) for i in range(stringLength))
@@ -151,8 +135,7 @@ def create_temp_dir(tmpdir=None):
151135
os.mkdir(path)
152136
except:
153137
raise RuntimeError(
154-
"Unable to create temporary working "
155-
"directory %s\n" % path + "Please specify run_location="
138+
"Unable to create temporary working " "directory %s\n" % path + "Please specify run_location="
156139
)
157140

158141
return path
@@ -172,6 +155,4 @@ def check_valid_port(port, lower_bound=1000, high_bound=60000):
172155
if lower_bound < port < high_bound:
173156
return
174157
else:
175-
raise ValueError(
176-
f"'port' values should be between {lower_bound} and {high_bound}."
177-
)
158+
raise ValueError(f"'port' values should be between {lower_bound} and {high_bound}.")

0 commit comments

Comments
 (0)