Python Forum
Run multiple process using subprocess - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Run multiple process using subprocess (/thread-35625.html)



Run multiple process using subprocess - Shiri - Nov-24-2021

How do I run my script proces1.py and process2.py into a single script to check if both the process are running and if so kill and restart the process again(I am passing arguments seperately in both the script need to achieve this from one script)
#Process1.py
for process in psutil.process_iter():
if (process.name().startswith('python3')) and ("new_scene" in process.cmdline()[1]):
    print('Process found')
    process.kill()
   time.sleep(5)
cmd='python3  /Desktop/Test/Script/new/new_scene.py --run  /Desktop/Test/Script/new/scenario/examples'
subprocess.call(cmd + sys.argv[1],shell=True)
break
else:
print('Process not found')
#Process2.py
for process in psutil.process_iter():
if (process.name().startswith('python3')) and ("Demo" in process.cmdline()[1]):
    print('Process found')
    process.kill()
   time.sleep(5)
cmd='python3  /Desktop/Test/Script/new/Demo.py --run  /Desktop/Test/Script/new/scenario/examples'
subprocess.call(cmd + sys.argv[1],shell=True)
break
else:
print('Process not found')



RE: Run multiple process using subprocess - ghoul - Nov-24-2021

(Nov-24-2021, 02:23 PM)Shiri Wrote: How do I run my script proces1.py and process2.py into a single script to check if both the process are running and if so kill and restart the process again(I am passing arguments seperately in both the script need to achieve this from one script)

From the link I shared, it is clear that if you want to run them in parallel you should go for 'Popen' while otherwise, you should go for 'subprocess.call'

cmd1 = "<pathtoscript1>"
cmd2 = "<pathtoscript2>"

process1 = Popen(cmd1, shell=True)
process2 = Popen(cmd2, shell=True)
Not something I have done before, but, yeah this looks correct.


RE: Run multiple process using subprocess - Shiri - Nov-24-2021

This part I got Thanks , but my doubt is in the if condition where both the scripts use different process name (process1.py searches for the process name and kill it how can i achieve this for process2.py in same script)


RE: Run multiple process using subprocess - ghoul - Nov-28-2021

(Nov-24-2021, 08:19 PM)Shiri Wrote: This part I got Thanks , but my doubt is in the if condition where both the scripts use different process name (process1.py searches for the process name and kill it how can i achieve this for process2.py in same script)

Combining the scripts just as is should be good even after which you could probably factor out repeated code into a function.

That would be good enough from me.