简体   繁体   中英

Python open and kill subprocess

I'm working on Widnows 7 (32 bits) and this is my code:

def start_mviewer_broker(broker_path, test_name):
""" The function starts the broker server"""
try:
    print("**** start_mviewer_broker ****")
    p = subprocess.Popen('start python ' + broker_path + ' ' + test_name, shell=True)
    return p
except:
    print("**** start_mviewer_broker - EXCEPTION ****")
    return 0


def kill_process(p):
""" The function kills the input running process"""
try:
    print("**** kill_process ****")
    p.terminate()
except:
    print("**** kill_process - EXCEPTION ****")
    pass

I have a few of problems. The only way to launch my subprocess is with shell=True option. If I change this option to False the subprocess is not launched.

Other problem is that kill process doesn't kill my process but not exception is raised.

Any idea?

You would want to change your code to the following:

def start_mviewer_broker(broker_path, test_name):
""" The function starts the broker server"""
try:
    print("**** start_mviewer_broker ****")
    return subprocess.Popen('python ' + broker_path + ' ' + test_name) # Note changed line here
except:
    print("**** start_mviewer_broker - EXCEPTION ****")
    return 0


def kill_process(p):
""" The function kills the input running process"""
try:
    print("**** kill_process ****")
    p.terminate()
except:
    print("**** kill_process - EXCEPTION ****")
    pass

The start part that you are running is not necessary. In fact, it is not an executable but is a cmd command. Hence, it requires a shell to run. This is why it wasn't working with just shell=False . However, upon removing it, you can now use shell=False . You then have the python process as the returned process instead of the shell that was used to spawn it. Killing the python process is what you want to do, not the shell, so after removing the start part, you would have the kill_process() code working properly.

BTW, shell=False is the default for subprocess.Popen() and has thus been left out in the above code. Also, setting p to the process and then immediately returning it seems like a waste of a line of code. It can be shortened to just returning it directly (as shown in the above code).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM