0

我无法确定Python模块打开的 Windows 程序 ( KeePass ) 的状态。subprocess调用 KeePass 程序很简单,但是一旦调用,我似乎无法确定它是否已成功打开。

我阅读了Popen.poll(),Popen.wait()Popen.communicate()对象并对其进行了测试,但我似乎无法找到可以挂钩的状态。

示例:(# <--- What goes here to check status?下面的评论)

import subprocess as s
import os.path


keepass_app = 'C:\Program Files\KeePass Password Safe 2\KeePass.exe'
keepass_db = 'E:\Documents\test.kdbx'
pw_file = 'E:\\Documents\\test.md'


def check_each_pw(pw_file):
    
    for pw in pw_file:
        
        t = s.Popen([keepass_app, keepass_db, f'-pw:{pw}'], stdin=s.PIPE, stdout=s.PIPE, stderr=s.PIPE)
        
        if  : # <--- What goes here to check status?

            print(f'{pw} is not a valid password')
            t.terminate()

        else:
            print(f'{pw} is the correct password!')
            t.terminate()


check_each_pw(pw_file)

编辑1:

插入到上面的代码中, ,对和值output, errors = t.communicate()的结果相同。b'' b''outputerror

        t = s.Popen([keepass_app, keepass_db, f'-pw:{pw}'], stdin=s.PIPE, stdout=s.PIPE, stderr=s.PIPE)
        
        output, errors = t.communicate()
        
        if errors == b'':
            print(f'{pw} is the correct password!')
            print(output, errors)
            t.terminate()

        else:
            print(f'{pw} is not a valid password.!')
            print(output, errors)
            t.terminate()

结果: 第一行pw_file是密码错误。KeePass 数据库未打开;GUI 显示弹出窗口:

在此处输入图像描述

...需要手动干预才能关闭。第二行pw_file是正确的密码。KeePass 成功打开。但是您可以看到,t.communicate()两次尝试的终端输出都是相同的。没有什么可挂钩的。

PS E:\Documents\python\pw_program> python .\pw_prog.py
abc is the correct password!
b'' b''
test is the correct password!
b'' b''

同样的事情t.wait()0而不是b''价值,没有什么可挂钩的):

        t = s.Popen([keepass_app, keepass_db, f'-pw:{pw}'], stdin=s.PIPE, stdout=s.PIPE, stderr=s.PIPE)
        
        errors = t.wait()
        
        if errors == 0:
            print(f'{pw} is the correct password!')
            print(errors)
            t.terminate()

        else:
            print(f'{pw} is not a valid password.')
            print(errors)
            t.terminate()
PS E:\Documents\python\pw_program> python .\pw_prog.py
abc is the correct password!
0
test is the correct password!
0

同样的事情也适用于t.poll()

        t = s.Popen([keepass_app, keepass_db, f'-pw:{pw}'], stdin=s.PIPE, stdout=s.PIPE, stderr=s.PIPE)
        
        errors = t.poll()
        
        if errors is None:
            print(f'{pw} is the correct password!')
            print(errors)
            t.terminate()

        else:
            print(f'{pw} is not a valid password.')
            print(errors)
            t.terminate()
PS E:\Documents\python\pw_program> python .\pw_prog.py
abc is the correct password!
None
test is the correct password!
None

我也尝试过替换s.check_calland s.check_output,不行!

4

1 回答 1

2

利用

output, errors = t.communicate()

获取变量的日志。输出将显示输出日志,错误将在崩溃时显示错误。

您也可以使用t.wait()它将等待进程终止并在成功执行的情况下返回 0。在崩溃的情况下,它的值将不是 0。

于 2021-11-09T05:53:47.730 回答