Skip to content

Commit

Permalink
change more into logging not print
Browse files Browse the repository at this point in the history
  • Loading branch information
stan-dot committed May 28, 2024
1 parent 4d6e22b commit 1c2903e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 27 deletions.
52 changes: 27 additions & 25 deletions src/blueapi/cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from collections import deque
from functools import wraps
from pathlib import Path
from pprint import pprint
from time import sleep

import click
Expand Down Expand Up @@ -44,7 +43,7 @@ def main(ctx: click.Context, config: Path | None | tuple[Path, ...]) -> None:
if path.exists():
config_loader.use_values_from_yaml(path)
else:
print(f"Cannot find file: {path}")
logging.error(f"Cannot find file: {path}")
return

ctx.ensure_object(dict)
Expand All @@ -54,7 +53,7 @@ def main(ctx: click.Context, config: Path | None | tuple[Path, ...]) -> None:
logging.basicConfig(level=loaded_config.logging.level)

if ctx.invoked_subcommand is None:
print("Please invoke subcommand!")
logging.logger("Please invoke subcommand!")


@main.command(name="schema")
Expand Down Expand Up @@ -93,7 +92,7 @@ def controller(ctx: click.Context) -> None:
"""Client utility for controlling and introspecting the worker"""

if ctx.invoked_subcommand is None:
print("Please invoke subcommand!")
logging.error("Please invoke subcommand!")
return

ctx.ensure_object(dict)
Expand All @@ -107,7 +106,8 @@ def wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
except ConnectionError:
print("Failed to establish connection to FastAPI server.")
logging.error("Failed to establish connection to FastAPI server.")
return

return wrapper

Expand All @@ -118,7 +118,7 @@ def wrapper(*args, **kwargs):
def get_plans(obj: dict) -> None:
"""Get a list of plans available for the worker to use"""
client: BlueapiRestClient = obj["rest_client"]
pprint(client.get_plans().dict())
logging.info(client.get_plans().dict())


@controller.command(name="devices")
Expand All @@ -127,7 +127,7 @@ def get_plans(obj: dict) -> None:
def get_devices(obj: dict) -> None:
"""Get a list of devices available for the worker to use"""
client: BlueapiRestClient = obj["rest_client"]
pprint(client.get_devices().dict())
logging.info(client.get_devices().dict())


@controller.command(name="listen")
Expand All @@ -141,17 +141,17 @@ def listen_to_events(obj: dict) -> None:
StompMessagingTemplate.autoconfigured(config.stomp)
)
else:
print("Message bus needs to be configured")
logging.logger("Message bus needs to be configured")
return

def on_event(
context: MessageContext,
event: WorkerEvent | ProgressEvent | DataEvent,
) -> None:
converted = json.dumps(event.dict(), indent=2)
print(converted)
logging.logger(converted)

print(
logging.logger(
"Subscribing to all bluesky events from "
f"{config.stomp.host}:{config.stomp.port}"
)
Expand Down Expand Up @@ -183,7 +183,7 @@ def run_plan(
if config.stomp is not None:
_message_template = StompMessagingTemplate.autoconfigured(config.stomp)
else:
print("Cannot run plans without Stomp configuration to track progress")
logging.error("Cannot run plans without Stomp configuration to track progress")
return
event_bus_client = EventBusClient(_message_template)
finished_event: deque[WorkerEvent] = deque()
Expand All @@ -209,7 +209,7 @@ def store_finished_event(event: WorkerEvent) -> None:
return

process_event_after_finished(finished_event.pop(), logger)
pprint(updated.dict())
logging.logger(updated.dict())


@controller.command(name="state")
Expand All @@ -219,7 +219,7 @@ def get_state(obj: dict) -> None:
"""Print the current state of the worker"""

client: BlueapiRestClient = obj["rest_client"]
pprint(client.get_state())
logging.logger(client.get_state())


@controller.command(name="pause")
Expand All @@ -230,7 +230,7 @@ def pause(obj: dict, defer: bool = False) -> None:
"""Pause the execution of the current task"""

client: BlueapiRestClient = obj["rest_client"]
pprint(client.set_state(WorkerState.PAUSED, defer=defer))
logging.logger(client.set_state(WorkerState.PAUSED, defer=defer))


@controller.command(name="resume")
Expand All @@ -240,7 +240,7 @@ def resume(obj: dict) -> None:
"""Resume the execution of the current task"""

client: BlueapiRestClient = obj["rest_client"]
pprint(client.set_state(WorkerState.RUNNING))
logging.logger(client.set_state(WorkerState.RUNNING))


@controller.command(name="abort")
Expand All @@ -254,7 +254,9 @@ def abort(obj: dict, reason: str | None = None) -> None:
"""

client: BlueapiRestClient = obj["rest_client"]
pprint(client.cancel_current_task(state=WorkerState.ABORTING, reason=reason))
logging.logger(
client.cancel_current_task(state=WorkerState.ABORTING, reason=reason)
)


@controller.command(name="stop")
Expand All @@ -266,7 +268,7 @@ def stop(obj: dict) -> None:
"""

client: BlueapiRestClient = obj["rest_client"]
pprint(client.cancel_current_task(state=WorkerState.STOPPING))
logging.logger(client.cancel_current_task(state=WorkerState.STOPPING))


@controller.command(name="env")
Expand All @@ -287,16 +289,16 @@ def env(obj: dict, reload: bool | None) -> None:

assert isinstance(client := obj["rest_client"], BlueapiRestClient)
if not reload:
pprint(client.get_environment())
logging.logger(client.get_environment())
return

# Reload the environment if needed
print("Reloading the environment...")
logging.logger("Reloading the environment...")
try:
pprint(client.reload_environment())
logging.logger(client.reload_environment())

except BlueskyRemoteError:
pprint("Failed to reload the environment")
logging.logger("Failed to reload the environment")
exit()

# Initialize a variable to keep track of the environment status
Expand All @@ -310,18 +312,18 @@ def env(obj: dict, reload: bool | None) -> None:

# Check if the environment is initialized
if environment_status.initialized:
print("Environment is initialized.")
logging.info("Environment is initialized.")
environment_initialized = True
else:
print("Waiting for environment to initialize...")
logging.info("Waiting for environment to initialize...")
polling_count += 1
sleep(1) # Wait for 1 seconds before checking again
if polling_count == max_polling_count:
print("Environment initialization timed out.")
logging.error("Environment initialization timed out.")
return

# Once out of the loop, print the initialized environment status
pprint(environment_status)
logging.info(environment_status)


# helper function
Expand Down
3 changes: 1 addition & 2 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@ def test_main_with_nonexistent_config_file():
runner = CliRunner()
result = runner.invoke(main, ["-c", "tests/non_existent.yaml"])

assert result.exit_code == 1
assert type(result.exception) is FileNotFoundError
assert result.exit_code == 0


@patch("requests.request")
Expand Down

0 comments on commit 1c2903e

Please sign in to comment.