How can PyQt call a Python script?

To call a Python script in PyQt, you can use the QProcess class to run an external program or script.

Here is a simple example demonstrating how to call a Python script in PyQt.

from PyQt5.QtCore import QProcess
from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QPushButton

class MyDialog(QDialog):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        button = QPushButton("调用Python脚本")
        button.clicked.connect(self.call_python_script)
        layout.addWidget(button)
        self.setLayout(layout)

    def call_python_script(self):
        process = QProcess(self)
        process.start("python", ["path/to/your_script.py"])
        process.waitForFinished()
        output = process.readAllStandardOutput().data().decode()
        print(output)

if __name__ == "__main__":
    app = QApplication([])
    dialog = MyDialog()
    dialog.show()
    app.exec_()

In the example above, we created a MyDialog class as the main dialog, which has a button that, when clicked, will call a Python script.

In the “call_python_script” method, we create a QProcess object and use the start method to specify the path of the Python script to be called. Feel free to replace the script path with your own.

Next, we use the waitForFinished method to wait for the script to finish executing and use the readAllStandardOutput method to retrieve the script’s output. In this example, we simply print the output to the console, but you can handle it however you want.

Please make sure you have installed the PyQt library before running this code. You can install the PyQt library in Python using the following command:

pip install pyqt5
bannerAds