Skip to content Skip to sidebar Skip to footer

Execute Command To A Python Script From Separate Python Script?

I'm trying to send a command from one python script to another running in terminal. I'm running two python scripts on an RPi running Raspbian. The first script is a loop that waits

Solution 1:

If you want to run a script and send information through stdin then in Qt the best option is to use QProcess:

import os.path
import sys

from PySide2.QtCore import QProcess
from PySide2.QtWidgets import QApplication, QPushButton, QSpinBox, QVBoxLayout, QWidget

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))


classMainWindow(QWidget):
    def__init__(self):
        QWidget.__init__(self)

        self.btn = QPushButton("test")
        self.spinbox = QSpinBox()

        self.process = QProcess()
        self.process.readyReadStandardError.connect(self.handle_readyReadStandardError)
        self.process.readyReadStandardOutput.connect(
            self.handle_readyReadStandardOutput
        )
        self.process.setProgram(sys.executable)
        script_path = os.path.join(CURRENT_DIR, "script.py")
        self.process.setArguments([script_path])
        self.process.start()

        layout = QVBoxLayout(self)
        layout.addWidget(self.spinbox)
        layout.addWidget(self.btn)
        self.btn.released.connect(self.btnpress)

    defbtnpress(self):
        number = self.spinbox.value()

        msg = "{}\n".format(number)
        self.process.write(msg.encode())

    defhandle_readyReadStandardError(self):
        print(self.process.readAllStandardError().data().decode())

    defhandle_readyReadStandardOutput(self):
        print(self.process.readAllStandardOutput().data().decode())


app = QApplication(sys.argv)

window = MainWindow()
window.show()
app.exec_()

Note: You don't have to run the script in a second shell as the script itself starts it.

Solution 2:

Subprocesses make sense when there is a clear parent/child relationship. This sounds more like you have two independent agents which occasionally need to communicate. There are various inter-process communication (IPC) mechanisms depending on your needs, the most basic being signals, where either process can send the other a single bit of information to notify it that some event occurred. For more complex needs, set up shared memory, or talk over a socket or a FIFO.

Solution 3:

i think that you have to add a third party, like:

  1. DATABASE
  2. REDIS
  3. File

but you cannot not send a command from a running script to another running script, because the CLI script wait command from his shell only. greetings

Post a Comment for "Execute Command To A Python Script From Separate Python Script?"