如何使用 python 终止外部程序或 window

How to terminate external program or window using python

我正在尝试关闭程序,在本例中为 spotify,但我不断遇到语义错误。这是我的代码:

sup_programs.txt

{ 
'spotify': ['C:/Users/Daniiar/AppData/Roaming/Spotify/Spotify.exe']
}

脚本:

class Path(object):
    import ast
    sup_programs_txt = open('sup_programs.txt', 'r')
    s_p = sup_programs_txt.read()
    paths = ast.literal_eval(s_p)
    sup_programs_txt.close()
paths = Path().paths
program_name = 'spotify'


def open_program(path_name):
    import subprocess
    subprocess.Popen(path_name)
    open_program(paths[program_name])


def close_program(path_name):
    import subprocess
    p = subprocess.Popen(path_name)
    p.terminate()


yes = input(" ... ")
if 'close' in yes or 'yes' in yes:
    close_program(paths[program_name])
else:
    print('too bad')

我使用了 kill() 和 terminate() 它们都没有用而且 os.system('TASKKILL ') 是否还有其他方法或我错误地使用了现有方法?

顺便说一句,我正在使用 windows 10 和 python 3.5 。感谢您的帮助

你的open_program函数是递归的???

无论如何,要打开你的程序,你可以通过路径名来完成。然后它 returns 一个子进程的句柄。 要关闭它,只需调用该句柄上的终止方法

下面的示例打开记事本,等待 3 秒,然后将其关闭。

import time
import subprocess

def open_program(path_name):

    return subprocess.Popen(path_name)

def close_program(p):
    p.terminate()

p=open_program("notepad")
time.sleep(3)
close_program(p)