【发布时间】:2014-01-01 07:35:54
【问题描述】:
我有以下我想用 Python 编写的 shell 脚本(当然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 进程,但我不知道如何混合字符串和文件。
【问题讨论】:
-
不能使用
StringIO对象来提供流程输入;请改用subprocess.PIPE。 -
@MartijnPieters 正如我所说的(最后一句),“我知道我应该使用 subprocess.communicate() 而不是 StringIO 将字符串发送到 grep 进程,但我不知道如何混合使用两者字符串和文件。”
-
为什么不从打开的文件对象中读取,写入管道?如果没有打开的文件,写替代文本。
-
为什么不使用 grep?
-
哦,好的。你可以使用一些库以完全 Python 的方式来完成它。但我理解你的意思。
标签: python subprocess