Search code examples
pythonnetwork-programmingtcp

how to send a string between two python programs


I need this for a project that I am making but I am not sure how to do it.

I'm look in for syntax like:
SENDER.py

string = "Hello"
send(hello)

READER.py

string = read()
print(string)

EDIT
Made a solution.
https://github.com/Ccode-lang/simpmsg


Solution

  • If both programmers are on different computers, you can try using sockets

    server.py

    import socket
    
    s = socket.socket()
    port = 12345
    s.bind(('', port))
    s.listen(5)
    c, addr = s.accept()
    print "Socket Up and running with a connection from",addr
    while True:
        rcvdData = c.recv(1024).decode()
        print "S:",rcvdData
        sendData = raw_input("N: ")
        c.send(sendData.encode())
        if(sendData == "Bye" or sendData == "bye"):
            break
    c.close()
    

    client.py

    import socket
    
    s = socket.socket()
    s.connect(('127.0.0.1',12345))
    while True:
        str = raw_input("S: ")
        s.send(str.encode());
        if(str == "Bye" or str == "bye"):
            break
        print "N:",s.recv(1024).decode()
    s.close()
    

    If you want to store it first so the other programmer can read it next time use files

    sender.py

    file1 = open("myfile.txt","w")
    file1.write("hello")
    file1.close()
      
    

    reader.py

    file1 = open("myfile.txt","r")
    data = file1.read()
    file1.close()
    print(data)