无法在 python 中强制终止程序

Unable to force program termination in python

我编写了一个程序,它通过 subprocess 库从自身调用另一个程序,然后通过 sys.exit().

自行终止

但这并没有那么简单。应该有一个问题清单。 (注意,不会是脚本本身,而是通过pyinstaller创建的这个脚本的应用)

  1. 当我转到任务管理器时,在详细信息选项卡中,我看到有 4 个 test.exe,其中 2 个 运行 在当前文件夹中,另外 2 个在 APPDATA\Local\test
  2. os.remove(o)未执行
  3. path + f'\{k}.txt' 只保存在 APPDATA\Local\testf'{k}test.txt' 只保存到当前文件夹

显然,该程序根本不是从 appdata 启动的,但事实并非如此,因为在任务管理器中显示了它,甚至显示了两次。这种行为的原因是什么?以及如何修复它?

UPD:我确保文件只保存在upadte中,在else:之后写os.chdir(path)。但是第一次执行还是无法完成。

import sys
import os
import time


path = os.path.dirname(os.getenv('APPDATA')) + '\Local\test'
try:
    os.mkdir(path)
except OSError:
    pass
if not os.path.isfile(path + '\test.exe'):
    with open(path + '\info.txt', 'w', encoding='utf-8') as f:
        f.write(sys.argv[0])
    subprocess.call(['copy', sys.argv[0], path + '\test.exe'], shell=True)
    subprocess.call(path + '\test.exe', shell=True)
    sys.exit()
else:
    with open(path + '\info.txt', 'r', encoding='utf-8') as f:
        o = f.readline()
        if os.path.isfile(o):
            try:
                os.remove(o)
            except:
                pass

k = 0
while True:
    time.sleep(5)
    with open(path + f'\{k}.txt', 'w', encoding='utf-8') as f:
        f.write('test message 1')
    with open(f'{k}test.txt', 'w', encoding='utf-8') as f:
        f.write('test message 2')
    k += 1

首先,您问了很多彼此不相关的问题。其次,我不确定您在这里想要达到什么目的,但我将为您提供一个简短的答案。

  1. 使用 PyInstaller(带有 -F 标志)创建的应用程序部署了两个进程。一个用于提取可执行文件的内容并在代码执行后进行清理,第二个用于您的程序本身。此外,您正在使用 subprocess 调用可执行文件,因此它将变成 4 个进程。

  2. 创建可执行文件后,sys.argv[0] 将等于可执行文件本身的路径。因此,您不能调用 os.remove() 来删除可执行文件本身。

  3. 我不确定这个问题,但是 os.path.dirname(os.getenv('APPDATA')) 会被翻译成用户的 AppData 路径,但是 f'{k}test.txt' 会被翻译成可执行文件所在的当前可执行文件路径位于.

我解决了通过 taskkill 终止进程的问题。因此,else 之后的代码如下所示:

os.chdir(path)
with open(path + '\info.txt', 'r', encoding='utf-8') as f:
    o = f.readline()
    if os.path.isfile(o):
        subprocess.call(['TASKKILL', '/IM', 'test.exe', '/F'], shell=True)
        os.remove(o)

在这样做时,我将两个程序的名称设置为不同,以便正确终止进程。