How to Expand Variables When Running the grep Command on Python

Asked 2 years ago, Updated 2 years ago, 112 views

In the code below, only the one in the test.txt from the array using grep is
I'd like to print out , but I don't know if the grep output is stored well in the variable, but I get an error no matter how many times I try.I don't know how to solve it, so please let me know.

#coding:UTF-8                                                                                                                                                                                                                                                                                           
import subprocess                                                                                                                                                                                                                                                                                                                                                                                                                                    

animal=["dog", "cat", "horse", "pig", "bird" ]
WORD = [ ]
cmd = "grep-c{}test.txt"                                                                                                                                                                                                                                                                                  

for i in range (len(animal)) :                                                                                                                                                                                                                                                                                   
  c=subprocess.check_output(cmd.format(animal[i]).split())                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  if int(c)>0:                                                                                                                                                
    WORD.append (animal[i])                                                                                                                                               

for i in range (len(WORD)):                                                                                                                               
  print("WORD[i]=%s"%WORD[i])

The following error occurred:

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    c=subprocess.check_output(cmd.format(animal[i]).split())
  File "C:\Users\aveni\AppData\Local\Programs\Python\Python38-32\lib\subprocess.py", line411, check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "C:\Users\aveni\AppData\Local\Programs\Python\Python38-32\lib\subprocess.py", line 512, in run
    raiseCalledProcessError(retcode,process.args,
subprocess.CalledProcessError: Command '['grep', '-c', 'pig', 'test.txt'] 'return non-zero exit status 1.

python python3 grep

2022-09-29 22:01

2 Answers

subprocess.check_output issues a CalledProcessError when the exit status of the command you executed is non-zero, and grep has an exit code of 0 only when the string you are looking for matches. check_output was

#-*-coding:utf-8-*-
import subprocess

animal=["dog", "cat", "horse", "pig", "bird" ]
WORD = [ ]
cmd = "grep-c{}test.txt"

for ani in animal:
    c=subprocess.run(cmd.format(ani).split(), capture_output=True)
    if int(c.stdout)>0:
        WORD.append(ani)

For win WORD:
    print("WORD[i]=%s"%w)

If the grep command only determines if there is a string, I think it is better to use the exit code (c.returncode).


2022-09-29 22:01

If you use subprocess.check_output(), you will be capturing subprocess.CalledProcessError.

Also, this has nothing to do with the main topic, but if the search word contains blank characters (TAB, spaces, etc.), the code in the question field will generate an error.The following lists the search terms in a single quote and specifies shell=True in subprocess.check_output().

import subprocess

animal=['dog', 'cat', 'horse', 'pig', 'bird', 'wild boar']
WORD = [ ]
cmd = r "grep-c'{}'test.txt"

for name in animal:
  try:
    c=subprocess.check_output (cmd.format(name), shell=True)
  except subprocess.CalledProcessError as ex:
    if ex.returncode==1:##None match
      c=0##c=ex.output
    elifex.returncode==2:##Error occurred
      print(ex)
      break

  if int(c)>0:
    WORD.append(name)

for i in range (len(WORD)):
  print(f'WORD[{i}] = {WORD[i]}')


2022-09-29 22:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.