gpt4 book ai didi

python - 使用 StringIO 作为标准输入与 Popen

转载 作者:太空狗 更新时间:2023-10-29 17:46:45 24 4
gpt4 key购买 nike

我有以下 shell 脚本,我想用 Python 编写(当然 grep . 实际上是一个复杂得多的命令):

#!/bin/bash

(cat somefile 2>/dev/null || (echo 'somefile not found'; cat logfile)) \
| grep .

我试过这个(无论如何都缺少与 cat logfile 等效的东西):

#!/usr/bin/env python

import StringIO
import subprocess

try:
myfile = open('somefile')
except:
myfile = StringIO.StringIO('somefile not found')

subprocess.call(['grep', '.'], stdin = myfile)

但我收到错误 AttributeError: StringIO instance has no attribute 'fileno'

我知道我应该使用 subprocess.communicate() 而不是 StringIO 将字符串发送到 grep 进程,但我不知道如何混合使用字符串和文件。

最佳答案

p = subprocess.Popen(['grep', '...'], stdin=subprocess.PIPE, 
stdout=subprocess.PIPE)
output, output_err = p.communicate(myfile.read())

关于python - 使用 StringIO 作为标准输入与 Popen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20568107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com