简体   繁体   English

如何将值从 python 脚本发送到另一个脚本?

[英]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.因此,我想将我在第一个脚本中找到的值发送到脚本 2 中的无限线程 function。我无法将第一个脚本导入第二个,因为我还从脚本 2 中获取另一个值到脚本 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.在第二个代码中,同时运行了 2 个不同的无限循环函数。 In the 1st function, the data from the arduino is constantly being read continuously and uninterruptedly.在第1个function中,从arduino中不断读取数据,不间断。 The 2nd function should print the number which coming from the 1st code.第二个 function 应该打印来自第一个代码的数字。 So actually there is nothing I can change in code 1. I am generating the number value.所以实际上我无法在代码 1 中更改任何内容。我正在生成数字值。 I need to send it to code 2 somehow.我需要以某种方式将它发送到代码 2。 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.任何睡眠等。我不能使用任何中断方法,因为在代码 1 中,相机应该不间断地工作。

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).编辑:如果你有像你提到的 CameraFeed 这样的连续数据流,你可以使用具有这样模式的队列(在这种情况下你真的不需要第二个 class,你可以在不同的类中实现 CameraFeed 和 CameraDataConsumer) .

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.如果dum线程没有向tis线程发送数据,可以使用tis的send_data方法通过main function向其发送数据,并从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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从另一个 python 脚本向 python 脚本发送多个“用户输入”? - How can I send multiple “user input” to python script from another python script? 如何从一个 Python 脚本发送信号以触发另一个脚本? - How can I send a signal from one Python script to trigger another? 如何将数据从python脚本发送到Matplotlib? - How can I send data from a python script to Matplotlib? 如何将Python脚本中的JSON对象发送到jQuery? - How can I send a JSON object from a Python script to jQuery? 如何将变量从一个 Python 脚本传递到另一个? - How can I pass a variable from one Python Script to another? 如何在 Python 脚本中运行另一个 Python 脚本? - How can I run another Python script in a Python script? 在 Python 中,如何同时从主脚本运行另一个 Python 脚本并在停止主脚本时将其关闭? - In Python, how can I run another Python script from the main script at the same time and close it when I stop the main script? 如何将数据从一个python脚本文件发送到pygtk中的另一个 - how to send data from one python script file to another in pygtk 如何从php执行python脚本并从python发送curl请求? - How can I execute a python script from php and send a curl request from python? 将变量从一个Python脚本发送到另一个 - Send a Variable from one Python Script to another
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM