gpt4 book ai didi

python - 如何跳过打印命令输出并仅从 os.system 命令获取返回值?

转载 作者:行者123 更新时间:2023-11-28 21:27:15 24 4
gpt4 key购买 nike

考虑以下示例 -

Python 2.4.3 (#1, Jan 14 2011, 00:20:04)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system("grep -i beatles blur.txt")
Blur's debut album Leisure (1991) incorporated the sounds of Madchester and shoegazing. Following a stylistic change.influenced by English guitar pop groups such as The Kinks, The Beatles and XTC.
0
>>> os.system("grep -i metallica blur.txt")
256
>>>

因此,在这种情况下,我不希望在 Python shell 上打印具有搜索关键字的行,我只想要返回值,即如果关键字存在则为 0,否则为非零。如何实现?

最佳答案

你只需要使用 grep-q 键:

$ python
Python 2.7.3rc2 (default, Apr 5 2012, 18:58:12)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system("grep -iq igor /etc/passwd")
0
>>> os.system("grep -iq oleg /etc/passwd")
256
>>>

我必须注意 -q 不是 grep 的可移植 key ,它只能与 GNU grep(Linux 等)一起使用。

当你想让它在所有系统上工作时,你必须使用popen/subprocess.Popen和流的重定向。

>>> import subprocess
>>> null = open(os.devnull, "w")
>>> grep = subprocess.Popen(shlex.split("grep -i oleg /etc/passwd"), stderr = null, stdout = null)
>>> grep.communicate()
(None, None)
>>> print grep.returncode
1
>>> grep = subprocess.Popen(shlex.split("grep -i igor /etc/passwd"), stderr = null, stdout = null)
>>> grep.communicate()
(None, None)
>>> print grep.returncode
0

关于python - 如何跳过打印命令输出并仅从 os.system 命令获取返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11398798/

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