将os.system()输出重定向到.txt文件

时间:2016-08-08 13:32:29

标签: python

我是Python的新手。我有Unix命令列表("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev"),我想运行它们并将整个输出重定向到.txt文件。我搜索了很多,但没有得到正确的解决方案,或者我错误地理解了事情。

我可以使用此for循环获取stdout上的输出,但我无法重定向到文件。

def commandsoutput():
    command = ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev")

    for i in command:
        print (os.system(i))

commandsoutput()

2 个答案:

答案 0 :(得分:3)

os.system返回命令的退出代码,而不是其输出。它也被弃用了。

改为使用subprocess

import subprocess

def commandsoutput():
     command = ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev")

     with open('log.txt', 'a') as outfile:
         for i in command:
              subprocess.call(i, stdout=outfile)

commandsoutput()

答案 1 :(得分:1)

此答案使用os.popen,它允许您在文件中写入命令的输出:

import os
def commandsoutput():
    commands = ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev")
    with open('output.txt','a') as outfile:
        for command in commands:
            outfile.write(os.popen(command).read()+"\n")
commandsoutput()