【发布时间】:2019-05-17 10:18:30
【问题描述】:
我在树莓派上运行一个 python 脚本,它将键盘输入读取到一个字符串,并将通过 TCP 发送该字符串。我制作了两个脚本,一个读取输入,一个可以在需要时发送字符串。我如何使用一个字符串并在两个脚本中使用它来阅读和写作?
我使用了一个文本文档。只是因为 sd 卡我想要实现两个脚本之间的连接
阅读部分:
#loops for Barcode_Data
def Create_File():
file = open("Barcode_data.txt", "w")
file.write(" // ")
file.close()
empty = ''
def Barcode_Read():
Barcode_Data= input("Input: ",)
print(Barcode_Data)
file = open("Barcode_data.txt", "a")
file.write(Barcode_Data)
file.write(" // ")
file.close()
#Loop that will only run once
Create_File()
#Loop that will run continuesly
while True:
Barcode_Read()
TCP 服务器:
#TCP server
def TCP_Connect(socket):
socket.listen()
conn, addr = socket.accept()
with conn:
data = conn.recv(1024)
if data == b'Barcode_Data':
tcp_file = open("Barcode_data.txt", "r")
Barcode_Data = tcp_file.read()
tcp_file.close()
conn.sendall(Barcode_Data.encode('utf-8'))
elif data == b'Clear Barcode_Data':
tcp_file = open("Barcode_data.txt", "w")
tcp_file.write(" // ")
tcp_file.close()
#TCP Socket setup
HOST = '' # Standard loopback interface address (localhost)
PORT = 1025 # Port to listen on (non-privileged ports are > 1023)
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
#Loop that wil run continuesly
while True:
TCP_Connect(s)
【问题讨论】:
-
你能分享示例代码吗?
-
在原帖中添加了我的代码