简体   繁体   English

一个python进程为另一个python进程提供信息

[英]One python process providing information for another python process

I know that similar questions occasionally appear 我知道偶尔也会出现类似的问题

communication between 2 programs in python or Communication between two python scripts python中的2个程序之间的通信两个python脚本之间的通信

but my problem is much more simple. 但我的问题要简单得多。 I have two python processes continuously running on the same computer and slave process occasionally needs three float numbers from master process. 我有两个在同一台计算机上连续运行的python进程,从属进程有时需要主进程提供三个浮点数。

Not being a programming expert, I would reserve three float slots somewhere in computer memory, which would be constantly updated by the master process, and the slave process would simply read this memory slots when it needed information. 如果不是编程专家,我会在计算机内存中的某个位置保留三个浮动插槽,这些浮动插槽将由主进程不断更新,而从属进程将在需要信息时简单地读取此内存插槽。 So essentially master is talking all the time and slave is listening only when it needs information. 因此,从本质上讲,主机一直在说话,而从机仅在需要信息时才在听。

Is that possible to do without much fuss and effort? 不用大惊小怪和努力就可以做到吗? If possible, keep answers simple, as I am not an programming expert. 如果可能的话,请简单回答,因为我不是编程专家。

It depends on the level of programming expert you're not, how quickly you need these numbers to be updated, and what OS you're on. 这取决于您不是编程专家的水平,需要多少时间来更新这些数字以及所使用的操作系统。

All that being said, the "Easy" way is simply to write them to a file (or files) that the slave process monitors for change, and reads when they're updated. 简而言之,“简便”方法就是将它们写入从属进程监视更改的一个或多个文件中,并在更新时读取。

Could the two processes (foo and bar below) not simply be threads of a master process? 难道两个进程(下面的foo和bar)不只是主进程的线程吗?

import time
import threading

x = 0.0
y = 0.0
z = 0.0
lock = threading.RLock()

def foo():
    global lock
    while True:
        time.sleep(10)
        with lock:
            print x, y, z

def bar():
    global x, y, z, lock
    while True:
        time.sleep(2)
        with lock:
            x += 0.5
            y += 0.6
            z += 0.7

fooThread = threading.Thread(target=foo)
fooThread.daemon = True
barThread = threading.Thread(target=bar)
barThread.daemon = True

barThread.start()
fooThread.start()

The 'lock' may not be required, but is good practice in multithreaded programming. “锁”可能不是必需的,但在多线程编程中是很好的做法。

In the end I have used RPyC library ( https://rpyc.readthedocs.org/en/latest/ ). 最后,我使用了RPyC库( https://rpyc.readthedocs.org/en/latest/ )。 Easy to use and powerful. 易于使用且功能强大。

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

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