简体   繁体   中英

How can I send a value from a python script to another script?

For example the first script:

from secondScript import Second
    ---
    ""
    ""
    ""
    while True:
        lastResult = <a list> --> I need to send this result to other script
    ---

My other script

class Second:
    def __init__(self):
     
        ""
        ""
        ""
        self.dum = Thread(target=self.func1)
        self.dum.deamon = True
        self.dum.start()

        self.tis = Thread(target=self.func2, args= <a list>)
        self.tis.deamon = True
        self.tis.start()

    def func1(self):
        while True:
            ""
            ""
            ""
 
    def func2(self, lastResult):
        while True:
            print(lastResult)

As a result, I want to send the value which I found in the first script to a infinity thread function in script 2. I can't import first script to second because I am also getting another values from script 2 to script 1.

Edit:

We can think of it like: There is a part of my program that is already running. We can say that I am getting real time images from the camera. While the whole code is running, it also generates a number value continuously and uninterruptedly. All of these operations are done in the 1st file. While the 1st file continues to work, it needs to continuously send this number to the 2nd file. In the second code, 2 different infinite loop functions are running at the same time. In the 1st function, the data from the arduino is constantly being read continuously and uninterruptedly. The 2nd function should print the number which coming from the 1st code. So actually there is nothing I can change in code 1. I am generating the number value. I need to send it to code 2 somehow. I'm not sure how to edit the code you wrote. Any sleep etc. I can't use any interrupt method because in code 1 the camera should work without interruption.

In first script:

print(lastResult, end='\n', file=sys.stdout, flush=True)

In other script and other thread:

second = Second()
...
for lastResult in sys.stdin:
    lastResult = lastResult[:-1]
    second.func2(lastResult)
...

Ok this answers your question, but I changed a bit the structure. I would do it as follows:

EDIT: If you have streams of continuous data like the CameraFeed you mentioned, you can use a Queue with a pattern like this (You don't really need the Second class in this case, you can implement the CameraFeed and CameraDataConsumer in different classes).

If the dum thread does not send data to the tis thread, you can use the send_data method of tis to send data to it through main function and remove the queue from CameraFeed.

from threading import Event, Thread
from queue import Queue, Full
import time

class CameraFeed(Thread):
    def __init__(self, queue):
        super().__init__()
        # This event is used to stop the thread
        # Initially it is unset (False)
        self._stopped_event = Event()
        self._queue = queue
        self._data = []

    def run(self):
        # sample_data is for demo purposes remove it and 
        # fetch data however you do it
        sample_data = iter(range(10**10))
        # Loop as long as the stopped event is not set
        while not self._stopped_event.is_set():
            # Get data from camera this is mock data
            data = next(sample_data)
            # Put data in the list for data to be sent
            self._data.append(data)
            # Get the next available item from the list
            data = self._data.pop(0)
            try:
                # This tries to puts in the queue
                # if queue is at max capacity raises a Full Exception
                self._queue.put_nowait(data)
                print('CameraFeed, sent data:', data)
            except Full:
                # If exception occures, put the data back to list
                self._data.insert(0, data)

    def stop(self):
        # Sets the stopped event, so the thread exits the run loop
        self._stopped_event.set()
        

class CameraDataConsumer(Thread):
    def __init__(self, queue):
        super().__init__()
        self._stopped_event = Event()
        self._queue = queue

    def run(self):
        while not self._stopped_event.is_set():
            # Waits for data from queue
            data = self._queue.get(block=True)
            # If data is None then do nothing
            if data is None:
                continue
            print('CameraConsumer, got data:', data)

    def send_data(self, data):
        """Method to send data to this thread from main probably"""
        self._queue.put(data, block=True)

    def stop(self):
        # Set the stopped event flag
        self._stopped_event.set()
        # Try to put data to queue, to wake up the thread
        try:
            self._queue.put_nowait(Data(None, EventType.OPERATION))
        except Full:
            # If queue is full, don't do anything it is probably
            # safe to assume that setting the stop flag is sufficient
            print('Queue is full')


# Create a Queue with capacity 1000
queue = Queue(maxsize=1000)
dum = CameraFeed(queue)
dum.start()

tis = CameraDataConsumer(queue)
tis.start()

# time.sleep is for demo purposes
time.sleep(1)
tis.stop()
dum.stop()
tis.join()
dum.join()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM