diff --git a/README.md b/README.md index d16f14663d2892b02a34afdefda03debe59207aa..917837da216e50280706bcd8a8591026713ea744 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,124 @@ -# PySide Multiprocessing +# pycmp: Python Module for Multiprocess Communication with PySide6 UIs +CMP (Communication Multiprocess Python module) is a Python module designed to facilitate communication between multiple processes while utilizing PySide for graphical user interfaces (GUIs). This module aims to provide a seamless solution for building applications with parallel processing capabilities and interactive UI components. +Features +* Multiprocess Communication: CMP enables efficient communication between multiple Python processes, allowing for concurrent execution of tasks. -## Getting started +* PySide Integration: CMP seamlessly integrates with PySide, a Python binding for the Qt framework, to create interactive and visually appealing user interfaces. -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +* Event Handling: CMP provides robust event handling mechanisms, allowing processes to communicate and synchronize events effectively. -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! +# Installation -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://gitlab.tugraz.at/flexsensor/pyside-multiprocessing.git -git branch -M main -git push -uf origin main +You can install CMP using pip: +```bash +pip install git+https://github.com/agentsmith29/fstools.cmp.git@main ``` -## Integrate with your tools - -- [ ] [Set up project integrations](https://gitlab.tugraz.at/flexsensor/pyside-multiprocessing/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) +# Usage -*** +Here's a simple example demonstrating how to use CMP: -# Editing this README +```python +from PySide6.QtCore import Signal +import cmp -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. +class ChildProcess(cmp.CProcess): -## Suggestions for a good README -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. + def __init__(self, state_queue, cmd_queue, kill_flag, *args, **kwargs): + super().__init__(state_queue, cmd_queue, kill_flag, *args, **kwargs) -## Name -Choose a self-explaining name for your project. + # The signal (add_two_finished) name mus correspond to the signal in the control class "ChildProcessControl" + # in order to get executed. + # The function (add_two) and function's signature name must correspond to the function in the control class + @cmp.CProcess.register_signal(signal_name='add_two_finished') + def add_two(self, num1: int, num2: int): + # "return" automatically sends the result to the control class and triggers the signal with the + # name "add_two_finished" + return num1 + num2 -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. +class ChildProcessControl(cmp.CProcessControl): + add_two_finished = Signal(int, name='test_call_finished') -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. + def __init__(self, parent, *args, **kwargs): + super().__init__(parent, *args, **kwargs) + # Register the child process + self.register_child_process(ChildProcess) -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. + # Create a body for your function. This does not necessarily have to include code, you can just print a message + # or add "pass", a comment, or a docstring. + @cmp.CProcessControl.register_function() + def add_two(self, num1: int, num2: int): + print("I will add two numbers in a separate process") +``` +Use your control class in your main application +```python +import logging +import sys + +from PySide6.QtCore import Signal +from PySide6.QtWidgets import QDialog, QApplication, QPushButton, QMessageBox, QVBoxLayout +from rich.logging import RichHandler + +sys.path.append('./src') +from mp_process import ChildProcessControl + + +class Form(QDialog): + on_text_converted = Signal(str) + + def __init__(self, parent=None): + super().__init__(parent) + + child_con = ChildProcessControl(self) + child_con.internal_log_enabled = True + child_con.internal_log_level = logging.INFO + + self.btn_start = QPushButton("Start") + self.btn_start.clicked.connect(lambda: child_con.add_two(1, 2)) + # add the button to the layout + layout = QVBoxLayout() + layout.addWidget(self.btn_start) + self.setLayout(layout) + + # Connect the signal to the slot + child_con.add_two_finished.connect(self.two_numbers_added) + + def two_numbers_added(self, result): + # Message box + msg = QMessageBox() + msg.setIcon(QMessageBox.Information) + msg.setText(f"The result is {result}") + msg.setWindowTitle("Result") + msg.exec() + + def closeEvent(self, arg__1): + self.destroyed.emit() + + +if __name__ == '__main__': + # Set up logging + FORMAT = "%(name)s %(message)s" + logging.basicConfig( + level=logging.DEBUG, format=FORMAT, datefmt="[%X]", handlers=[RichHandler()] + ) + + try: + app = QApplication(sys.argv) + form = Form() + form.show() + app.exec() + except KeyboardInterrupt: + print("KeyboardInterrupt") + sys.exit(0) # print(f"{os.getpid()} -> call_without_mp with {a}, {b}, {c}!") +``` -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. +In this example, when the button is clicked, CMP emits the "button_clicked" event, which triggers the process_function to be executed in a separate process. +Contributing -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +We welcome contributions from the community! If you encounter any issues or have suggestions for improvements, please feel free to open an issue or submit a pull request on the GitHub repository. -## License -For open source projects, say how it is licensed. +# License -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +This project is licensed under the GNU GENERAL PUBLIC LICENSE Version 3.0. See the LICENSE file for details. diff --git a/examples/example1/example1.py b/examples/example1/example1.py index 24e023c1f7553deffee31cabed776b84175bf9fd..beb27755e765fcd558692f14fd34672eada29798 100644 --- a/examples/example1/example1.py +++ b/examples/example1/example1.py @@ -1,72 +1,52 @@ -# -*- coding: utf-8 -*- -""" -Author(s): Christoph Schmidt <christoph.schmidt@tugraz.at> -Created: 2023-10-19 12:35 -Package Version: -""" -import signal +import logging import sys -from multiprocessing import Process, Queue, Pipe -from threading import Thread -from PySide6.QtCore import QObject, Signal, SIGNAL -from PySide6.QtWidgets import QDialog, QApplication, QTextBrowser, QLineEdit, QVBoxLayout, QMainWindow, QMessageBox +from PySide6.QtCore import Signal +from PySide6.QtWidgets import QDialog, QApplication, QPushButton, QMessageBox, QVBoxLayout +from rich.logging import RichHandler -from mp_process import ChildProc, ChildControl +sys.path.append('./src') +from mp_process import ChildProcessControl class Form(QDialog): - on_text_converted = Signal(str) def __init__(self, parent=None): super().__init__(parent) - child_con = ChildControl(self, internal_logging=True) - - child_con.call_without_mp_finished.connect(self.updateUI) - child_con.call_without_mp2_changed.connect(self.updateUI2) + child_con = ChildProcessControl(self) + child_con.internal_log_enabled = True + child_con.internal_log_level = logging.INFO - - self.browser = QTextBrowser() - self.lineedit = QLineEdit('Type text and press <Enter>') - self.lineedit.selectAll() + self.btn_start = QPushButton("Start") + self.btn_start.clicked.connect(lambda: child_con.add_two(1, 2)) + # add the button to the layout layout = QVBoxLayout() - layout.addWidget(self.browser) - layout.addWidget(self.lineedit) + layout.addWidget(self.btn_start) self.setLayout(layout) - self.lineedit.setFocus() - self.setWindowTitle('Upper') - #self.lineedit.returnPressed.connect(lambda: child_con.call_without_mp(1, 2, c=3)) - self.lineedit.returnPressed.connect(lambda: child_con.call_all()) - - #self.emitter.register(self.on_text_converted, self.updateUI) - def test(self): - #Signal(str) - self.data_to_child.put(self.to_child.__name__) - #self.lineedit.clear() + # Connect the signal to the slot + child_con.add_two_finished.connect(self.two_numbers_added) + def two_numbers_added(self, result): + # Message box + msg = QMessageBox() + msg.setIcon(QMessageBox.Information) + msg.setText(f"The result is {result}") + msg.setWindowTitle("Result") + msg.exec() - def updateUI(self, text): - print("updateUI: ", text) - self.browser.append(str(text)) - - def updateUI2(self, text, text2, text3): - print("updateUI2: ", text) - self.browser.append("->" + str(text) + "+" + str(text2) + "=" + str(text3)) - - def closeEvent(self, event): - print("closeEvent") - #try: + def closeEvent(self, arg__1): self.destroyed.emit() - #except KeyboardInterrupt: - # print("KeyboardInterrupt") - #event.ignore() - if __name__ == '__main__': + # Set up logging + FORMAT = "%(name)s %(message)s" + logging.basicConfig( + level=logging.DEBUG, format=FORMAT, datefmt="[%X]", handlers=[RichHandler()] + ) try: app = QApplication(sys.argv) @@ -75,5 +55,4 @@ if __name__ == '__main__': app.exec() except KeyboardInterrupt: print("KeyboardInterrupt") - sys.exit(0) - + sys.exit(0) # print(f"{os.getpid()} -> call_without_mp with {a}, {b}, {c}!") diff --git a/examples/example1/mp_process.py b/examples/example1/mp_process.py index 4f2c538e9a55c2c2cd6350ceeeb1e0b930d24630..953751c892b9489905c9d345d6c57ec9c30f208a 100644 --- a/examples/example1/mp_process.py +++ b/examples/example1/mp_process.py @@ -1,66 +1,34 @@ -# -*- coding: utf-8 -*- -""" -Author(s): Christoph Schmidt <christoph.schmidt@tugraz.at> -Created: 2023-10-19 12:35 -Package Version: -""" -import os -import sys -import time - from PySide6.QtCore import Signal -sys.path.append('./src') import cmp -class Sceleton: - - def call_without_mp(self, a, b, c=None, **kwargs): - raise NotImplementedError() - - -class ChildProc(cmp.CProcess, Sceleton): - - def __init__(self, state_queue, cmd_queue, enable_interal_logging): - super().__init__(state_queue, cmd_queue, enable_interal_logging=enable_interal_logging) +class ChildProcess(cmp.CProcess): - @cmp.CProcess.register_signal() - def call_without_mp(self, a, b, c=None, **kwargs): - print(f"{os.getpid()} -> call_without_mp with {a}, {b}, {c} and {kwargs}!") - time.sleep(1) - return c + def __init__(self, state_queue, cmd_queue, kill_flag, *args, **kwargs): + super().__init__(state_queue, cmd_queue, kill_flag, *args, **kwargs) - @cmp.CProcess.register_signal('_changed') - def call_without_mp2(self, a, b, c=None, **kwargs): - print(f"{os.getpid()} -> call_without_mp2 with {a}, {b}, {c} and {kwargs}!") - time.sleep(1) - return b, c, b+c + # The signal (add_two_finished) name mus correspond to the signal in the control class "ChildProcessControl" + # in order to get executed. + # The function (add_two) and function's signature name must correspond to the function in the control class + @cmp.CProcess.register_signal(signal_name='add_two_finished') + def add_two(self, num1: int, num2: int): + # "return" automatically sends the result to the control class and triggers the signal with the + # name "add_two_finished" + return num1 + num2 - #@CProccess.register_function - def call_all(self, *args, **kwargs): - self.call_without_mp(1, 2, c=3) - self.call_without_mp2(4, 7, c=5) -class ChildControl(cmp.CProcessControl, Sceleton): - call_without_mp_finished = Signal(int) - call_without_mp2_changed = Signal(int, int, int) +class ChildProcessControl(cmp.CProcessControl): + add_two_finished = Signal(int, name='test_call_finished') - def __init__(self, parent, internal_logging): - super().__init__(parent, internal_logging=internal_logging) - self.register_child_process(ChildProc(self.state_queue, self.cmd_queue, enable_interal_logging=internal_logging)) - - @cmp.CProcessControl.register_function() - def call_without_mp(self, a, b, c=None): - pass - #print(f"{os.getpid()} -> call_without_mp with {a}, {b}, {c}!") - - @cmp.CProcessControl.register_function() - def call_without_mp2(self, a, b, c=None, **kwargs): - pass + def __init__(self, parent, *args, **kwargs): + super().__init__(parent, *args, **kwargs) + # Register the child process + self.register_child_process(ChildProcess) + # Create a body for your function. This does not necessarily have to include code, you can just print a message + # or add "pass", a comment, or a docstring. @cmp.CProcessControl.register_function() - def call_all(self): - pass - #print(f"{os.getpid()} -> Executing call_all in Control Class.") + def add_two(self, num1: int, num2: int): + print("I will add two numbers in a separate process")