【问题标题】:Translate standard output memory file to string of English text as if a print command were being used将标准输出内存文件翻译成英文字符串,就像使用打印命令一样
【发布时间】:2012-03-10 18:33:26
【问题描述】:

我正在为我知道存在的特定文件运行查找命令。我想获取该文件的路径,因为我不想假设我知道该文件的位置。我的理解是我需要重定向标准输出,运行命令并捕获输出,重新连接标准输出,然后检索结果。当我检索结果时出现问题......我无法破译它们:

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

我找到了所有我想要的路径,问题是 path_to_file 产生了这个:

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'

我不知道该怎么办。我想要的是类似于 print 命令提供的东西:

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

如何使该输出可用于打开文件?如果我能得到打印命令的结果,我就可以打开我想要的文件。

如果我被误导了,请重新定位问题。谢谢!

【问题讨论】:

    标签: python unix find stdout stringio


    【解决方案1】:

    您无法通过更改sys.stdout 来捕获子进程的输出。您捕获的似乎是来自交互式 Python 解释器(IPython?)的一些 ANSI 转义序列。

    要获取外部命令的输出,您应该使用subprocess.check_output():

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

    在这种特殊情况下,我通常根本不会调用外部命令,而是使用os.walk() 在 Python 进程中查找文件。

    编辑:以下是使用os.walk() 查找文件的方法:

    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"))
    

    【讨论】:

    • 斯文,谢谢您的回复。我正要测试它。你介意详细说明 os.walk 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 2015-08-31
    • 2020-09-29
    • 2011-09-04
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    相关资源
    最近更新 更多