【问题标题】:Read output from a Python Executed Script从 Python 执行脚本读取输出
【发布时间】:2014-07-02 15:57:06
【问题描述】:

我目前正在创建一个程序来从驱动器中提取文件。我想问一下我如何读取使用 python shell 显示的输出?例如:

while i<len(drives):
    print 'Searching for file in:', drives[i]
    print ''
    for root, dirs, files in os.walk(drives[i]):
        for file in files:
            if file.endswith(".vmdk"):
                print os.path.join(root, file)
            if file.endswith(".vbox"):
                print os.path.join(root,file)
    i+=1

我想读取print os.path.join(root,file) 的输出,将其输入另一个命令。这可能吗?

【问题讨论】:

    标签: python loops operating-system output computer-forensics


    【解决方案1】:

    我不知道如何捕获print os.path.join(root, file) 的输出,但您也可以在打印前将调用os.path.join(root,file) 的输出保存在一个变量中。然后你可以使用这个变量来调用你的命令。例如:

    while i<len(drives):
        print 'Searching for file in:', drives[i]
        print ''
        for root, dirs, files in os.walk(drives[i]):
            for file in files:
                if file.endswith(".vmdk") or file.endswith(".vbox"):
                    filePath = os.path.join(root, file)
                    print filePath
                    // call your command here using 'filePath'
        i+=1
    

    【讨论】:

    • 嘿,谢谢你的回答。真的很感激(:不过我还有一个问题。如果在 os.path.join(root,file) 命令中返回多个文件怎么办?谢谢!
    • 根据documentationos.path.join 总是返回单个值。如果您想跟踪循环中生成的所有路径,可以考虑使用list
    最近更新 更多