Python Forum

Full Version: Run multiple process using subprocess
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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')
(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.
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)
(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.