bash 存储 os.system 或 os.popen 的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2817416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Store value of os.system or os.popen
提问by chrissygormley
I want to grep the error's out of a log file and save the value as an error. When I use:
我想从日志文件中提取错误并将该值保存为错误。当我使用:
errors = os.system("cat log.txt | grep 'ERROR' | wc -l")
I get the return code that the command worked or not. When I use:
我得到命令是否有效的返回码。当我使用:
errors = os.popen("cat log.txt | grep 'ERROR' | wc -l")
I get what the command is trying to do.
我明白了命令想要做什么。
When I run this in the command line I get 3 as thats how many errors there are.
当我在命令行中运行它时,我得到 3,因为这是有多少错误。
Can anyone suggest another way in Python that will allow me to save the value of this bash command?
任何人都可以在 Python 中提出另一种方法来让我保存这个 bash 命令的值吗?
Thanks
谢谢
回答by Olivier Verdier
popenis deprecated. Use subprocessinstead. For example, in your case:
popen已弃用。改用子流程。例如,在您的情况下:
p1 = Popen(["cat", "log.txt"], stdout=PIPE)
p2 = Popen(["grep", "ERROR"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
回答by SilentGhost
You're probably looking for:
您可能正在寻找:
grep -c 'ERROR' log.txt
Generally for spawning a subprocess you need to use subprocessmodule. There are plenty example, I'm sure you wouldn't get lost.
通常要生成子进程,您需要使用subprocess模块。有很多例子,我相信你不会迷路。
回答by Il-Bhima
First open a pipe using popen as you did.
首先像你一样使用 popen 打开一个管道。
p = os.popen("cat log.txt | grep 'ERROR' | wc -l")
Now just access the pipe like a normal file:
现在只需像普通文件一样访问管道:
output = p.readline()
This will be a string so you'll still have to do some additional parsing, but that shouldn't be a problem.
这将是一个字符串,因此您仍然需要进行一些额外的解析,但这应该不是问题。
EDIT: Ok, it seems that from Python 2.6 onwards, os.popen is deprecated. I thus defer my answer to whoever answered correctly using subprocess.Popen instead. Thanks for that guys.
编辑:好的,似乎从 Python 2.6 开始, os.popen 已被弃用。因此,我将我的答案推迟给使用 subprocess.Popen 正确回答的人。谢谢你们。
回答by jfs
How many 'ERROR'in the file:
'ERROR'文件中有多少:
nerrors = open('log.txt').read().count('ERROR') # put whole file in memory
How many lines that contain 'ERROR':
包含多少行'ERROR':
nerrors = sum(1 for line in open('log.txt') if 'ERROR' in line) # line at a time
If you must use the literal bash line then in Python 2.7+:
如果您必须使用文字 bash 行,那么在 Python 2.7+ 中:
from subprocess import check_output as qx
nerrors = int(qx("cat your_file.txt | grep 'ERROR' | wc -l", shell=True))
See Capturing system command output as a stringfor an implementation of check_output()for Python < 2.7.
有关Python < 2.7的实现,请参阅将系统命令输出捕获为字符串check_output()。

