title: extract strings from a binary file in python
body: <p>I have a project where I am given a file and i need to extract the strings from the file. Basically think of the "strings" command in linux but i'm doing this in python. The next condition is that the file is given to me as a stream (e.g. string) so the obvious answer of using one of the subprocess functions to run strings isn't an option either. </p>
  
  <p>I wrote this code:</p>
  
  <pre><code>def isStringChar(ch):
      if ord(ch) &gt;= ord('a') and ord(ch) &lt;= ord('z'): return True
      if ord(ch) &gt;= ord('A') and ord(ch) &lt;= ord('Z'): return True
      if ord(ch) &gt;= ord('0') and ord(ch) &lt;= ord('9'): return True
  
      if ch in ['/', '-', ':', '.', ',', '_', '$', '%', '\'', '(', ')', '[', ']', '&lt;', '&gt;', ' ']: return True
  
  # default out
  return False
  
  def process(stream):
  dwStreamLen = len(stream)
  if dwStreamLen &lt; 4: return None
  
  dwIndex = 0;
  strString = ''
  for ch in stream:
      if isStringChar(ch) == False:
          if len(strString) &gt; 4:
              #print strString
              strString = ''
      else:
          strString += ch
  </code></pre>
  
  <p>This technically works but is WAY slow. For instance, I was able to use the strings command on a 500Meg executable and it produced 300k worth of strings in less than 1 second. I ran the same file through the above code and it took 16 minutes. </p>
  
  <p>Is there a library out there that will let me do this without the burden of python's latency?</p>
  
  <p>Thanks!</p>