subprocess + grep for backslash terminated string

Viewed 67

I want to use subprocess to grep for a string that end in backslash:

product = "myProduct\"

so in bash, if I do:

zgrep -n 'myProduct\\' file_of_products.txt.gz

it works (I get a bunch of lines). Trying now in python:

import subprocess
product = "myProduct\\"
command = f"""zgrep -n "{product}" {filename}"""
return_code, output = subprocess.getstatusoutput(command)

I get;

'/bin/sh: 1: Syntax error: Unterminated quoted string'
1 Answers

You may use this refactored code with raw string and single quoting:

import subprocess
product = r"myProduct\\"
command = f"zgrep -n '{product}' '{filename}'"
return_code, output = subprocess.getstatusoutput(command)
Related