从终端的输出中找到一些特定的单词-Python

问题描述 投票:0回答:1

我要编写一个脚本,需要检查输出以查看是否成功。

例如:

我希望脚本在终端的输出中找到一些特定的单词,比如说单词“ password”和“ key.txt”

我使用subprocess.check_output,但出现错误。我的代码有什么问题?如何解决?

这是我的代码:

import subprocess

cmds=[]

# Add the command
cmds.append("ls -lah")

# The output
results=[]

# Execute the command
for cmd in cmds:
    results.append(subprocess.call(cmd, shell=True))

# Check the terminal's output and print "Successful"
# if there is a specific word in the output
res = subprocess.check_output(['password', 'key.txt'])
if res in cmds:
    print("SUCCESSFUL")
else:
    print("NO SUCCESS")

这是我得到的错误:

    Traceback (most recent call last):
  File "test.py", line 17, in <module>
    res = subprocess.check_output(['password', 'key.txt'])
  File "/usr/lib/python3.7/subprocess.py", line 395, in check_output
    **kwargs).stdout
  File "/usr/lib/python3.7/subprocess.py", line 472, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/lib/python3.7/subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.7/subprocess.py", line 1522, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'password': 'password'
python terminal subprocess
1个回答
0
投票

我发现它是如何工作的:

import subprocess
from subprocess import check_output

res = ('password')

# check the output
out = check_output(['ls', '-l'])
print(out)

# Show if it was successful or not
if res in out:
    print("*************** SUCCESSFUL ***************")
else:
    print("*************** NO SUCCESS ***************")
© www.soinside.com 2019 - 2024. All rights reserved.