如何使用python终止外部程序或窗口 [英] How to terminate external program or window using python

查看:43
本文介绍了如何使用python终止外部程序或窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试关闭程序,在这种情况下是 Spotify,但我不断收到语义错误.这是我的代码:

I am trying to close the program, in this case spotify, but I am keep getting semantic mistake. Here is my code:

sup_programs.txt

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 ')是否有其他方法或错误使用现有方法?

I used kill() and terminate() neither of them have worked and os.system('TASKKILL ') Is there any other methods or am using existing ones incorrectly?

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

BTW, I am using windows 10 and python 3.5 . Thank you for your help

推荐答案

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

your open_program function is recursive ???

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

Anyway, to open your program, you can do it by the path name. It then returns a handle on a subprocess. To close it, just call the terminate method on that handle

下面的例子打开记事本,等待 3 秒,然后关闭它.

example below opens notepad, waits 3 seconds, then closes it.

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)

这篇关于如何使用python终止外部程序或窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆