![](/img/trans.png)
[英]How to check the status of a shell script using subprocess module in Python?
[英]How to use Python `subprocess` to check status of external application on Windows?
我无法确定 Python subprocess
模块打开的 Windows 程序 ( KeePass ) 的状态。 调用 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()
, output
和error
值产生相同的b'' b''
。
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
和s.check_output
,不行!
用
output, errors = t.communicate()
获取变量中的日志。 输出将显示输出日志,错误将在崩溃时显示错误。
您也可以使用t.wait()
它将等待进程终止并在成功执行的情况下返回 0。 在崩溃的情况下,它将值为 0 以外的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.