Translate standard output memory file to string of English text as if a print command were being used

StackOverflow https://stackoverflow.com//questions/9649058

Question

I am running a find command for a particular file that I know exists. I would like to get the path to that file, because I don't want to assume that I know where the file is located. My understanding is that I need to redirect stdout, run the command and capture the output, re-hook-up standard output, then retrieve the results. The problem comes when I retrieve the results... I can't decipher them:

import os
from cStringIO import StringIO
stdout_backup = sys.stdout #Backup standard output
stdout_output = StringIO() 
sys.stdout = stdout_output #Redirect standard output
os.system("find . -name 'foobar.ext' -print") #Find a known file
sys.stdout = stdout_backup #re-hook-up standard output as top priority
paths_to_file = stdout_ouput.get_value() #Retrieve results

I find all the paths I could want, the trouble is that paths_to_file yields this:

Out[9]: '\n\x01\x1b[0;32m\x02In [\x01\x1b[1;32m\x027\x01\x1b[0;32m\x02]: \x01\x1b[0m\x02\n\x01\x1b[0;32m\x02In [\x01\x1b[1;32m\x028\x01\x1b[0;32m\x02]: \x01\x1b[0m\x02'

I have no idea what to do with this. What I wanted was something like what the print command provides:

./Work/Halpin Programs/Servers/selenium-server.jar

How do I make that output usable for opening a file? If I can get what the print command yeilds, I can open the file I want.

Please reorient the question if I am misguided. Thank you!

Was it helpful?

Solution

You cannot capture the output of a subprocess by changing sys.stdout. What you captured seems to be some ANSI escape sequences from your interactive Python interpreter (IPython?).

To get the output of an external command, you should use subprocess.check_output():

paths = subprocess.check_output(["find", ".", "-name", "foobar.ext"])

In this particular case, I usually wouldn't call an external command at all, but rather use os.walk() to find the files from right within the Python process.

Edit: Here's how to use os.walk() to find the files:

def find(path, pattern):
    for root, dirs, files in os.walk(path):
        for match in fnmatch.filter(files, pattern):
            yield os.path.join(root, match)

paths = list(find(".", "foobar.ext"))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top