Python打开和关闭子进程

2024-04-25 23:04:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究Widnows 7(32位),这是我的代码:

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

我有一些问题。启动子进程的唯一方法是使用shell=True选项。如果将此选项更改为False,则不会启动子进程。你知道吗

另一个问题是kill进程不会终止我的进程,但不会引发异常。你知道吗

你知道吗?你知道吗


Tags: thepathnametest进程deffunctionbroker
1条回答
网友
1楼 · 发布于 2024-04-25 23:04:56

您需要将代码更改为以下内容:

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

您正在运行的start部分不是必需的。实际上,它不是一个可执行文件,而是一个cmd命令。因此,它需要一个shell来运行。这就是为什么它不能只使用shell=False。但是,在删除它之后,现在可以使用shell=False。然后将python进程作为返回的进程,而不是用于生成它的shell。杀死python进程是您想要做的,而不是shell,因此在删除start部分之后,kill_process()代码就可以正常工作了。你知道吗

顺便说一句,shell=Falsesubprocess.Popen()的默认值,因此在上面的代码中被省略了。另外,将p设置到进程中,然后立即返回它似乎是在浪费一行代码。它可以缩短为直接返回(如上面的代码所示)。你知道吗

相关问题 更多 >

    热门问题