sharath
sharath

Reputation: 19

To redirect os.system() output to a .txt file

I'm new to Python. I have list of Unix commmands ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev") and I want to run them and redirect the entire output to a .txt file. I searched a lot but didn't get a proper solution, or I understood things wrongly.

I'm able to get the output on stdout with this for loop but I can't redirect to a file.

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()

Upvotes: 2

Views: 5154

Answers (2)

DeepSpace
DeepSpace

Reputation: 81654

os.system returns the exit code of the command, not its output. It is also deprecated.

Use subprocess instead:

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()

Upvotes: 3

Abdou
Abdou

Reputation: 13274

This answer uses os.popen, which allows you to write the output of the command in your file:

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()

Upvotes: 1

Related Questions