I used Java to implement a distributed algorithm Birman-Schiper-Stephenson
. Every time I run this program, I need to open three terminals and type command java Server 2
, java Client 0 2
, java Client 1 2
separately in three terminals to activate a server and two clients.
Now I want this process to be automatic and I try to use python to write a script to run those java files automatically. I tried the code as below:
import os
import thread
thread.start_new_thread(os.system('java Server 2'))
try:
thread.start_new_thread(os.system('java Client 0 2'))
thread.start_new_thread(os.system('java Client 1 2'))
except:
print "Error: unable to start thread"
However, there's something wrong with the multithreaded process. I have to terminate the Server process
then the Client process
can be activated. Can anybody tell me how to implement this multiprocess with shell commands by python?
os.system
blocks, so each thread you spawn is going to block the parent thread until execution is done (which, in the case of your java Server
call, probably means it will never exit).
A simple way to get around this is to use the subprocess
module (which is recommended for executing stuff you'd use os.system
for).
import subprocess
commands = [
'java Server 2',
'java Client 0 2',
'java Client 1 2'
]
# using subprocess.Popen will run sub-processes in parallel
java_procs = [subprocess.Popen(command, shell=True) for command in commands]
# now wait for the processes to finish?
for p in java_procs: p.wait()
If you need more serious multiprocessing/parallel process execution, the multiprocessing
module is usually a better recommendation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.