2017-03-27 45 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' 

就是這樣!功能齊全,通訊快速可靠。我知道總會有一些改進,但在大多數情況下,這種方法可以完美地工作。

相關問題