在Python中使用Linux重定向到文件命令

时间:2015-01-07 07:20:42

标签: python linux

我想使用Python将Linux的free命令的输出写入文件。

我尝试过以下但没有帮助:

 from subprocess import call
    call(["free",">","myfile"])

    f = open('myfile','w')
    f.write(subprocess.call(["free"]))

我是Python的新手,所以有人可以指导我使用Python将免费命令输出写入文件吗?

另外,我使用的Python是2.4。

我在一家使用python 2.4的公司工作

3 个答案:

答案 0 :(得分:1)

import subprocess

f = open('myfile', 'w')
subprocess.call('free', stdout=f)
f.close()

在较新版本的Python中,可以使用with来关闭文件,使用check_call来捕获free命令中的错误。但是你说你坚持使用Python 2.4,所以你去吧!

答案 1 :(得分:0)

这是python2.7

f.write(str(call(["free", ">", "myfile"])))

通过这个,您可以在myfile中编写命令输出。

from subprocess import call
f = open('myfile','w+')       # if you willing to read it simultaneously
f.write(str(call(["free", ">", "myfile"]))) # convert the data coming from shell to string using `str()` function.

f.seek(0)  # Reading from start set pointer to start of the file.
print f.read()

答案 2 :(得分:0)

您应该使用subprocess.Popen

示例:

import subprocess

cmd = "date"
fname = "output"

with open(fname, 'w+') as outf:
    subprocess.Popen(cmd, stdout=outf)

没有with-statement的文件访问:

outf = open(fname, 'w+')
try:
    subprocess.Popen(cmd, stdout=outf)
finally:
    outf.close()

是的,你应该更新你的Python版本。

供参考:

还请查看文档的这些部分,以获取有关不同常见用例的使用和示例的详细信息: