如何将bash命令的输出放在Python变量中?
如何将bash命令的输出放在Python变量中 我正在编写一个Python脚本,我想输入 bash命令:如何将bash命令的输出放在Python变量中?,python,Python,如何将bash命令的输出放在Python变量中 我正在编写一个Python脚本,我想输入 bash命令: rpm-qa-qf'{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}%{VENDOR}\n'| grep-v'Red Hat'| wc-l,并将其放在Python变量中,比如说R 之后我想做的是,Pythonif R!=0 然后运行一些Linux命令。 如何实现这一点?有多种选择,但最简单的方法可能是使用子流程。使用shell=True检查\u output(),尽管
rpm-qa-qf'{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}%{VENDOR}\n'| grep-v'Red Hat'| wc-l
,并将其放在Python变量中,比如说R
之后我想做的是,Pythonif R!=0
然后运行一些Linux命令。
如何实现这一点?有多种选择,但最简单的方法可能是使用
子流程。使用shell=True
检查\u output()
,尽管如果您不能完全控制传入的命令,这可能会造成安全隐患
import subprocess
var = subprocess.check_output('rpm -qa --qf '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH} %{VENDOR}\n' | grep -v 'Red Hat'|wc -l', shell = True)
var = int(var)
您需要使用shell=True
,否则将无法解释管道
如果您需要更多的控制,您可能想看看您可以在哪里做:
from plumbum.cmd import rpm, grep, wc
chain = rpm["-qa", "--qf", r"%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH} %{VENDOR}\n"] | grep["-v", "Red Hat"] | wc["-l"]
R = int(chain())
虽然我可能不会调用
wc
并在python中获得整个输出和计算其长度(更容易检查您是否得到了预期的行数,但是通过wc-l
管道传输会丢弃所有细节)我建议使用特使
,主要是因为API在90%的用例中使用更加直观
r = envoy.run('ls ', data='data to pipe in', timeout=2)
print r.status_code # returns status code
print r.std_out # returns the output.
有关更多详细信息,请参见本页。您可以使用标准输入法
#!/usr/bin/python
import sys
s = sys.stdin.read()
print s
然后您将运行一个bash命令,如下所示
echo "Hello" | ./myscript.py
输出
Hello
您可以使用Popen:
from subprocess import PIPE,Popen
p1 = Popen(["rpm", "-qa", "--qf", '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH} %{VENDOR}\n'],stdout=PIPE)
p2 = Popen(["grep", "-v", 'Red Hat'],stdin=p1.stdout,stdout=PIPE)
p1.stdout.close()
p3 = Popen(["wc", "-l"],stdin=p2.stdout,stdout=PIPE)
p2.stdout.close()
out,err = p3.communicate()
如果您只想检查grep是否返回了任何匹配项,那么忘记wc-l,只需检查grep返回的内容:
p1 = Popen(["rpm", "-qa", "--qf", '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH} %{VENDOR}\n'],stdout=PIPE)
p2 = Popen(["grep", "-v", 'Red Hat'],stdin=p1.stdout,stdout=PIPE)
p1.stdout.close()
out,err = p2.communicate()
if out:
...
或者只需使用check\u output
运行rpm
命令并检查字符串中的“Red Hat”
:
这与使用
grep-v
反转搜索,然后检查是否与wc匹配相同。您真的需要使用python脚本吗。也许jsut bash就足够了。你的问题不是很清楚,你能补充一些关于你的python脚本的细节吗。
out = check_output(["rpm", "-qa", "--qf", '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH} %{VENDOR}\n'])
if "Red Hat" not in out:
....