title: Is it possible to pass regex strings as args to a Python CLI tool using argparse?
body: <p>I'm writing a script to search a logfile for a given python regex pattern. Setting aside the fact that this would be <em>much</em> easier to do using a simple Bash script, can it be done in Python? Here's what I've run into:</p>
  <h3>Assumptions:</h3>
  <ul>
  <li>I'm trying to analyze the file <code>/var/log/auth.log</code>
  <ul>
  <li>(for the sake of simplicity, I'm omitting the ability to choose a file.)</li>
  </ul>
  </li>
  <li>the name of my cli module is <code>logscour</code>.</li>
  <li>for the sake of argument, <code>logscour</code> takes only one arg called <code>regex_in</code>.</li>
  </ul>
  <h3>Intended usage:</h3>
  <pre><code>[root@localhost]: # logscour '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
  </code></pre>
  <p>Should return the lines inside of <code>/var/log/auth.log</code> that contain an IPv4 address.</p>
  <p>I want to find a sort of anti-<code>re.escape()</code>, as I am in backslash-hell. Here's a snippet:</p>
  <pre><code>import re
  import argparse
  
  def main(regex_in, logfile='/var/log/auth.log'):
      ## Herein lies the problem!
      # user_regex_string = re.escape(regex_in) #&lt;---DOESN'T WORK, EVEN MORE ESCAPE-SLASHES
      # user_regex_string = r'{}'.format(regex_in) #&lt;---DOESN'T WORK
      user_regex_string = regex_in                 #&lt;---DOESN'T WORK EITHER GAHHH
      
      with open(logfile, 'rb+') as authlog:
          for aline in authlog:
              if re.match(user_regex_string, aline):
                  print aline
  
  if __name__ == '__main__':
      parser = argparse.ArgumentParser()
      parser.add_argument(&quot;regex_in&quot;, nargs=&quot;?&quot;, help=&quot;enter a python-compliant regex string. Parentheses &amp; matching groups not supported.&quot;, default=None)
      
      args = parser.parse_args()
      if not args.regex_in:
          raise argparse.ArgumentError('regex_in', message=&quot;you must supply a regex string&quot;)
      main(args.regex_in)
  </code></pre>
  <p>This is giving me back nothing, as one would expect due to the fact that I'm using Python2.7 and these are bytestrings I'm dealing with.</p>
  <p>Does anyone know a way to convert <code>'foo'</code> to <code>r'foo'</code>, or an &quot;opposite&quot; for <code>re.escape()</code>?</p>