我需要通过我的python脚本执行多个c ++程序。这些c ++程序就像客户端和服务器一样。所以我需要同时运行它们。但是脚本正在等待结束第一个c ++程序,然后开始下一个。 我在下面写的脚本:
import subprocess
import os
os.chdir("/home/My_Work/pgm_1")
cmd="gnome-terminal -e 'bash -c make;./pgm_1 exec bash'"
subprocess.Popen(cmd,shell=True)//control comes till here
os.chdir("/home/My_Work/pgm_2")
cmd2="gnome-terminal -e 'bash -c make;./pgm_2 exec bash'"
subprocess.Popen(cmd2,shell=True)
请帮我解决这个问题
答案 0 :(得分:0)
根据帖子中的评论,您的代码似乎无法正常运行。但是,当您运行它时,您可以使用此策略来管理同时运行这两个程序。我怀疑如果您的原始代码没有,下面的代码将会起作用;因此,如果您选择使用它,它将被视为多线程的指南。
要同时运行函数,请使用多线程。
# import the necessary modules
import thread
# define the functions that will manage the two programs
def prog1():
print 'Program 1 running'
os.chdir("/home/My_Work/pgm_1")
cmd="gnome-terminal -e 'bash -c make;./pgm_1 exec bash'"
subprocess.Popen(cmd,shell=True)//control comes till here
def prog2():
print 'Program 2 running!'
os.chdir("/home/My_Work/pgm_2")
cmd2="gnome-terminal -e 'bash -c make;./pgm_2 exec bash'"
subprocess.Popen(cmd2,shell=True)
# call the threads simultaneously
try:
thread.start_new_thread(prog1)
thread.start_new_thread(prog2)
except: # i don't know what kind of error to expect here, it is usually not a good idea to leave this blank!
print 'Threads failed to start!'
# keeps the program running
while 1:
pass