【问题标题】:Python how to use string in multiple scriptsPython如何在多个脚本中使用字符串
【发布时间】: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)

【问题讨论】:

  • 你能分享示例代码吗?
  • 在原帖中添加了我的代码

标签: python string


【解决方案1】:

您可以按原样使用此问题中的代码:Interprocess communication in Python

服务器进程:

from multiprocessing.connection import Listener

address = ('localhost', 6000)     # family is deduced to be 'AF_INET'
listener = Listener(address, authkey='secret password')
conn = listener.accept()
print 'connection accepted from', listener.last_accepted
while True:
    msg = conn.recv()
    # do something with msg
    if msg == 'close':
        conn.close()
        break
listener.close()

客户端进程:

from multiprocessing.connection import Client

address = ('localhost', 6000)
conn = Client(address, authkey='secret password')
conn.send('close')
# can also send arbitrary objects:
# conn.send(['a', 2.5, None, int, sum])
conn.close()

文档可在此处获得:https://docs.python.org/3.7/library/multiprocessing.html#multiprocessing-listeners-clients

【讨论】:

    猜你喜欢
    • 2018-03-14
    • 2016-04-30
    • 2021-07-23
    • 2019-01-25
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    相关资源
    最近更新 更多