How to save the output (stdout) of another program to a file using Python?

Asked

Viewed 88 times

1

Example, I give the command on the terminal:

import os

os.system('ipconfig')

This returns me the ipconfig equal to the command in CMD, but I need to take the result that showed in the terminal and save in a txt file that in my case is the resultado.txt, but I can’t.

Follows full code:

import os

def save(filename, info):
    file = open('{}'.format(filename), 'w', encoding='UTF-8')
    file.write(info + '\n')
    file.close()

save('resultado.txt', os.system('ipconfig'))

I even looked for similar questions, but I couldn’t locate anything conclusive.

2 answers

3

According to the documentation of os.system:

In Unix, the return value is the output status of the encoded process in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of function C system(), then the return value of the Python function is system dependent.

In Windows, the return value is the one returned by the system shell after running command. The shell is provided by the Windows environment variable COMSPEC: usually it is cmd.exe, that returns the output status of the command execution; on systems that use a non-native shell, refer to the shell documentation.

Then use os.system to obtain the output stdout of a program is not a good idea.

One option is to use the function run, module subprocess. Sort of like this:

from subprocess import run, PIPE


def save(filename, info):
    with open(filename, 'w', encoding='utf-8') as file:
        file.write(info)


result = run('ifconfig', stdout=PIPE)
save('resultado.txt', result.stdout.decode('utf-8'))

Note that we passed the argument stdout as subprocess.PIPE so that he may be captured. Moreover, result.stdout is a bytes Object, so that we use the method decode to convert it to a UTF-8 string.

Like run is relatively recent in Python (>= version 3.5), you can use the function check_output from the same module if you need an older support.

2


In another answer you will find the use of subprocess, much more elegant that the answer I present here. However, this is much simpler.

import os

def save(filename, comando):
    comando_completo = f"{comando} > {filename}"
    os.system(comando_completo)

save('resultado.txt', 'ipconfig')

I hope it helps

  • Sensational, worked perfectly, Thank you, Paul!

  • Just doubt this f" serves for what ?

  • 1

    f-string : example: print(f"O vavor é {sua_variavel}") is the equivalent of print("O valor é %s" % str(sua_variavel)). I think f-string came into existence from 3.7 - See more here

  • I didn’t know, now I’ve learned one more rsrs Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.