简体   繁体   中英

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"

I use subprocess.check_output but I get errors. 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 ***************")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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