以bash命令的结果,并使用Python中它 [英] Taking the results of a bash command and using it in python
问题描述
我试图用Python语言编写一个code,将采取自上而下的一些信息,并把它放到一个文件中。
我只想编写应用程序的名称,生成文件。我遇到的问题是,我不能得到的pidof命令的输出,所以我可以在Python中使用它。我的code是这样的:
I am trying to write a code in python that will take some information from top and put it into a file. I want to just write the name of the application and generate the file. The problem i am having is that i can't get the output of the pidof command so i can use it in python. My code looks like this :
import os
a = input('Name of the application')
val=os.system('pidof ' + str(a))
os.system('top -d 30 | grep' + str(val) + '> test.txt')
os.system('awk '{print $10, $11}' test.txt > test2.txt')
问题是,VAL总是0,但该命令返回我想要的PID。任何投入将是巨大的。
The problem is that val always has 0 but the command is returning the pid i want. Any input would be great.
推荐答案
一起来,使用输入()
气馁,因为它要求用户输入有效Python的前pressions。使用的raw_input()
而不是:
First up, the use of input()
is discouraged as it expects the user to type in valid Python expressions. Use raw_input()
instead:
app = raw_input('Name of the application: ')
接下来,从的返回值系统('的pidof')
不是PID,它是从出口code中的的pidof
命令,失败即零成功,非零。你想捕捉的pidof的输出
。
Next up, the return value from system('pidof')
isn't the PID, it's the exit code from the pidof
command, i.e. zero on success, non-zero on failure. You want to capture the output of pidof
.
import subprocess
# Python 2.7 only
pid = int(subprocess.check_output(['pidof', app]))
# Python 2.4+
pid = int(subprocess.Popen(['pidof', app], stdout=subprocess.PIPE).communicate()[0])
# Older (deprecated)
pid = int(os.popen('pidof ' + app).read())
下一行后失踪的的grep
的空间,并会导致像 grep1234
命令。使用字符串格式化操作符%
将使这更容易一点的景点:
The next line is missing a space after the grep
and would have resulted in a command like grep1234
. Using the string formatting operator %
will make this a little easier to spot:
os.system('top -d 30 | grep %d > test.txt' % (pid))
第三条线被严重引用,应该引起语法错误。当心单引号单引号里面。
The third line is badly quoted and should have caused a syntax error. Watch out for the single quotes inside of single quotes.
os.system("awk '{print $10, $11}' test.txt > test2.txt")
这篇关于以bash命令的结果,并使用Python中它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!