简体   繁体   English

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

[英]Find some specific words from terminal's output - Python

I'm gonna write a script and need to check the output to see if it was successful.我要写一个脚本,需要检查输出是否成功。

For example:例如:

I want the script to find some specific words in terminal's output, let say words "password" and "key.txt"我希望脚本在终端的输出中找到一些特定的词,比如“password”和“key.txt”

I use subprocess.check_output but I get errors.我使用 subprocess.check_output 但出现错误。 What is wrong with my code?我的代码有什么问题? How to fix it?如何解决?

This is my code:这是我的代码:

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")

And This is the error that I get:这是我得到的错误:

    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'

I've found how it works:我发现它是如何工作的:

import subprocess
from subprocess import check_output

kword = ('password')

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

# Show if it was successful or not
if kword in result:
    print("*************** SUCCESSFUL ***************")
else:
    print("*************** NO SUCCESS ***************")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM