我无法确定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''
output
error
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_call
and s.check_output
,不行!