I want to build a script that can be controlled while running from another scripts. For example I want to run my script like this:
~: Server &
If you are only trying to send commands one-directionally to a server, it is easier than you think, using Python's Sockets. The code samples are of course barebones in the sense that they do not do error handling, and do not call recv
multiple times to make sure the message is complete. This is just to give you an idea of how few lines of code it takes to process commands.
Here is a server program that simply receives messages and prints to stdout
. Note that we use threading so that the server can listen to multiple clients at once.
import socket
from threading import Thread
MAX_LENGTH = 4096
def handle(clientsocket):
while 1:
buf = clientsocket.recv(MAX_LENGTH)
if buf == '': return #client terminated connection
print buf
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
PORT = 10000
HOST = '127.0.0.1'
serversocket.bind((HOST, PORT))
serversocket.listen(10)
while 1:
#accept connections from outside
(clientsocket, address) = serversocket.accept()
ct = Thread(target=handle, args=(clientsocket,))
ct.start()
Here is a client program that sends commands to it.
import socket
import sys
HOST = '127.0.0.1'
PORT = 10000
s = socket.socket()
s.connect((HOST, PORT))
while 1:
msg = raw_input("Command To Send: ")
if msg == "close":
s.close()
sys.exit(0)
s.send(msg)