2017-03-27 47 views
1

我有2个python脚本。 1st是Flask服务器,第二个是NRF24L01接收器/发送器(在Raspberry Pi3上)脚本。两个脚本都在同一时间运行。我想在这两个脚本之间传递变量(变量不是常量)。我如何以最简单的方式做到这一点?Python脚本之间的通信

回答

1

python RPC设置如何?即在每个脚本上运行一个服务器,每个脚本也可以是一个客户端来相互调用远程过程调用。

https://docs.python.org/2/library/simplexmlrpcserver.html#simplexmlrpcserver-example

+0

谢谢。我会尝试。如果我会使用C,C++,我可以使用指针来做到这一点?但python不支持指针,对吗?另一个我的想法是将两个脚本合并,但是我恐怕会有慢程序? –

+0

为什么你认为你会有一个演出节目,你需要什么样的响应水平? – Sush

0

我想提出关于Sush的命题一个完整的解决方案筑底。在过去的几天里,我一直在努力解决两个进程之间的通信问题(我的情况 - 在同一台机器上)。有很多解决方案(套接字,RPC,简单RPC或其他服务器),但它们都有一些限制。对我而言,SimpleXMLRPCServer模块是我的工作。在各个方面都比直接插座操作快速,可靠并且更好。这可以从客户端完全关闭功能完整的服务器只是作为短:

from SimpleXMLRPCServer import SimpleXMLRPCServer 
quit_please = 0 

s = SimpleXMLRPCServer(("localhost", 8000), allow_none=True) #allow_none enables use of methods without return 
s.register_introspection_functions() #enables use of s.system.listMethods() 
s.register_function(pow) #example of function natively supported by Python, forwarded as server method 

# Register a function under a different name 
def example_method(x): 
    #whatever needs to be done goes here 
    return 'Enterd value is ', x 
s.register_function(example_method,'example') 

def kill(): 
    global quit_please 
    quit_please = 1 
    #return True 
s.register_function(kill) 

while not quit_please: 
    s.handle_request() 

我主要帮助15岁的文章中发现here

此外,很多教程使用s.server_forever()这是一个真正的痛苦,没有多线程干净地停止。

要与服务器通信的所有你需要做的基本上是2线:

import xmlrpclib 
serv = xmlrpclib.ServerProxy('http://localhost:8000') 

例子:

>>> import xmlrpclib 
>>> serv = xmlrpclib.ServerProxy('http://localhost:8000') 
>>> serv.example('Hello world') 
'Enterd value is Hello world' 

就是这样!功能齐全,通讯快速可靠。我知道总会有一些改进,但在大多数情况下,这种方法可以完美地工作。

相关问题