Skip to content

Instantly share code, notes, and snippets.

@lethee
Created September 13, 2012 13:09
Show Gist options
  • Save lethee/3714179 to your computer and use it in GitHub Desktop.
Save lethee/3714179 to your computer and use it in GitHub Desktop.
Test server/client apps Using Python's subprocess
import time
import sys
for i in range(5):
time.sleep(1)
sys.stdout.write("%d\n" % i)
sys.stdout.flush()
import subprocess
import time
import threading
import signal
import os
#############
server_cmd = "python server.py"
server_ready_pattern = "2"
client_cmd = "ls -al"
#############
def start_client(server_proc):
client = subprocess.call(client_cmd, shell=True)
print client
print "![test ] server"
os.kill(server_proc.pid, signal.SIGTERM)
def start_server():
proc = subprocess.Popen(server_cmd,shell=True,stdout=subprocess.PIPE)
while True:
time.sleep(0.1)
line = proc.stdout.readline()
if not line: break
print "![server]", line.strip()
if (line.strip() == server_ready_pattern):
threading.Thread(target=start_client, args=(proc,)).start()
proc.wait()
print "![test ] server killed"
if __name__ == '__main__':
start_server()
@lethee
Copy link
Author

lethee commented Sep 13, 2012

결과:

$ python test.py 
![server] 0
![server] 1
![server] 2
total 16
drwxr-xr-x   4 sean  staff   136 Sep 13 21:58 .
drwxr-xr-x  56 sean  staff  1904 Sep 13 20:50 ..
-rw-r--r--   1 sean  staff   108 Sep 13 21:36 server.py
-rw-r--r--   1 sean  staff   711 Sep 13 21:58 test.py
0
![test  ] server
![test  ] server killed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment