python在Linux中實現GRPC簡單命令

2021-09-01 10:23:27 字數 1888 閱讀 6542

先確認安裝python3後安裝grpc:

pip install grpcio

pip install protobuf

pip install grpcio-tools

2.編輯或使用服務方提供的 proto檔名.proto 檔案

3.編譯 proto檔名.proto 檔案

python -m grpc_tools.protoc -i./ --python_out=. --grpc_python_out=. proto檔名.proto
4.編寫server.py**

#coding:utf-8

from concurrent import futures

import time

import grpc

import proto檔名_pb2

import proto檔名_pb2_grpc

_one_day_in_seconds = 60 * 60 * 24

class greeter(proto檔名_pb2_grpc.greeterservicer):

# 工作函式

def sayhello(self, request, context):

print(request.name)

print(request.info)

message = "我是伺服器,您的訊息: " + request.name;

return proto檔名_pb2.helloreply(message = message)

def server():

# grpc 伺服器

server = grpc.server(futures.threadpoolexecutor(max_workers=10))

proto檔名_pb2_grpc.add_greeterservicer_to_server(greeter(), server)

server.add_insecure_port('[::]:50051')

print("服務已開啟,等待訊息...")

server.start() # start() 不阻塞,等待。

try:

while true:

time.sleep(_one_day_in_seconds)

except keyboardinterrupt:

server.stop(0)

if __name__ == '__main__':

server()

5.編寫cnt.py客戶端檔案

#coding:utf-8

from __future__ import print_function

import grpc

import proto檔名_pb2

import proto檔名_pb2_grpc

def run():

channel = grpc.insecure_channel('localhost:50051')

stub = proto檔名_pb2_grpc.greeterstub(channel)

response = stub.sayhello(proto檔名_pb2.hellorequest(name='我是客戶端,我想測試!',info='info'))

print("greeter client received: " + response.message)

if __name__ == '__main__':

run()

6.執行 python3 server.py 進入等待

7.另啟執行 python3 cnt.py, 觀察服務端出現提示及返回訊息即成功.

在Linux中公升級Python

由於寫的乙個東西,字元不對,所以決定在python3.0以上的環境中執行一下試試看 我用的是3.3.0的版本 wget tar xzvf python 3.3 0.tgz 進入解壓縮後的資料夾 cd python 3.3.0在編譯前先在 usr local建乙個資料夾python3 作為python...

python隨機選擇 在python中實現隨機選擇

想從乙個序列中隨機抽取若干元素,或者想生成幾個隨機數。random 模組有大量的函式用來產生隨機數和隨機選擇元素。比如,要想從乙個序列中隨機的抽取乙個元素,可以使用random.choice import random values 1,2,3,4,5,6 random.choice values ...

hash table在python中的實現

hash table 又稱為雜湊表,有鍵和值組成,陣列中方商品的 雜湊表總是將同樣的輸入對映到形同的索引 雜湊函式將不同的輸入對映到不同的索引 雜湊函式知道陣列有多大,只返回有效的索引。投票可以使用雜湊表 voted defcheck voter name if voted.get name pri...