Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python终止外部程序或窗口_Python_Python 3.x_Subprocess - Fatal编程技术网

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

如何使用python终止外部程序或窗口,python,python-3.x,subprocess,Python,Python 3.x,Subprocess,我试图关闭程序,在本例中是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.

我试图关闭程序,在本例中是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' 是否有其他方法或我不正确地使用现有方法

顺便说一句,我使用的是Windows10和python 3.5。感谢您的帮助

您的OpenU程序函数是递归的

无论如何,要打开程序,可以通过路径名来完成。然后返回子流程的句柄。 要关闭它,只需调用该句柄上的terminate方法

下面的示例打开记事本,等待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)

你得到了什么样的回溯?为什么启动一个新进程并终止它,会终止另一个已经运行的进程?你必须存储打开进程的p,并在这个p上使用p。终止于这个p,而不是该可执行文件的另一个实例。谢谢,我理解了我的错误。我不得不在现有流程上调用terminate。