-3

I'm running a python script on a raspberry pi that reads keyboard input to a string and will be sending that string through TCP. I've made two script one that reads the input and one that can send the string if needed. How can i use one string and use it in both scripts for readings and writings?

I've used an text document. Only becaue of the sd card i wanne achieve an connecting between the two scripts

Reading part:

#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 Server:

#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)
Gert-Jan
  • 1
  • 1

1 Answers1

-1

You can use the code from this question as is: Interprocess communication in Python

Server process:

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()

Client process:

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()

Documentation is available here: https://docs.python.org/3.7/library/multiprocessing.html#multiprocessing-listeners-clients

delica
  • 1,647
  • 13
  • 17