-
-
Notifications
You must be signed in to change notification settings - Fork 738
Allow Observer to be used as a context manager (fixes #1090) #1149
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Allow Observer to be used as a context manager (fixes #1090) #1149
Conversation
|
@BoboTiG kindly review the PR to the proposed improvement |
|
Thanks @Prosperibe12 ! That seems good for a first quick look. Can you add a line in the changelog and fix tests + linters? |
|
@BoboTiG I have made few changes to fix the tests, linters and updated the changelog. |
changelog.rst
Outdated
|
|
||
| **Other Changes** | ||
|
|
||
| - [core] Add context manager support to ``Observer`` class. The observer can now be used with a ``with`` statement for automatic start/stop management. (`#XXXX <https://github.com/gorakhargosh/watchdog/pull/1149>`__) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| - [core] Add context manager support to ``Observer`` class. The observer can now be used with a ``with`` statement for automatic start/stop management. (`#XXXX <https://github.com/gorakhargosh/watchdog/pull/1149>`__) | |
| - [core] Add context manager support to ``Observer`` class. The observer can now be used with a ``with`` statement for automatic start/stop management. (`#1090 <https://github.com/gorakhargosh/watchdog/pull/1149>`__) |
tests/utils.py
Outdated
| Provides some robustness for the otherwise flaky nature of asynchronous notifications. | ||
| """ | ||
| assert self.event_queue.get(timeout=timeout)[0] == expected_event | ||
| try: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You can revert this change.
|
This is a little bit hard to review. I would like a PR with only |
|
ok |
6e63504 to
6699a6f
Compare
|
@BoboTiG |
Fixes #1090
Adds context manager support to Observer to ensure
correct startup and teardown semantics.
Eg 1
class MyEventHandler(FileSystemEventHandler):
def on_any_event(self, event: FileSystemEvent) -> None:
print(event)
event_handler = MyEventHandler()
observer = Observer()
observer.schedule(event_handler, ".", recursive=True)
with observer:
while True:
time.sleep(1)
Eg 2
if name == "main":
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()