0

I use a script to run two script. the code like this:

import subprocess

subprocess.Popen("python a.py", shell=True)
subprocess.Popen("python b.py", shell=True)

but if I end the main script, the sub process of a.py and b.py are still runing. How to solve it?

added:

the a.py and b.py is two server scripts. When I end the main script using ctrl+c,and the two servers is not end up.So how to end the all process when I end the main script?

5
  • Try popen(“kill $!”, shell=True) though that would only kill last one and the answer below is better Commented Aug 6, 2018 at 11:02
  • You do not need shell=True, you are only introducing a security risk with that. Just do Popen(['python', 'a.py']). shell=True is useful only when you are using some shell feature (e.g. pipes/redirection/built-ins/expansions etc) and even most of those can actually be avoided. If you are just running an executable do not specify shell=True. Commented Aug 6, 2018 at 11:02
  • Have any reason to start a new python interpretor instead of simply calling import a.py or at least compile and exec? Commented Aug 6, 2018 at 11:34
  • @GiacomoAlzetta If I using shell=False, it give me an error:No such file or directory: 'python a.py'. Commented Aug 7, 2018 at 1:12
  • @XiaXuehai You should use Popen(["python", "a.py"]) not Popen("python a.py"). Or if you don't want to manually write the least do : import shlex and then Popen(shlex.split("python a.py"))) Commented Aug 10, 2018 at 7:18

1 Answer 1

3

By killing the processes.

import subprocess

p1 = subprocess.Popen("python a.py", shell=True)
p2 = subprocess.Popen("python b.py", shell=True)

# ... do things ...

p1.kill()
p2.kill()

You can also automate this with the atexit module:

import subprocess
import atexit

p1 = subprocess.Popen("python a.py", shell=True)
p2 = subprocess.Popen("python b.py", shell=True)
atexit.register(p1.kill)  # register for killing
atexit.register(p2.kill)

# ... do things ...
Sign up to request clarification or add additional context in comments.

1 Comment

THX, but the a.py and b.py is two server scripts. When I end the main script using ctrl+c,and the two servers is not end up.So can you tell me how to end the all process when I end the main script?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.