How to store command output in file

I need to store output of a system command in a text file.

eg:-

import os
os.system('ls -al')

Its output :

drwx------  2 root root  4096 Aug  7 12:08 .ssh
drwxr-xr-x  2 root root  4096 Feb 27  2021 Templates
-rw-r--r--  1 root root    63 Aug 11 20:29 txt
drwxr-xr-x  2 root root  4096 Oct 24 07:03 Videos
-rw-------  1 root root  6813 Jul 25 07:43 .viminfo
drwxr-xr-x  3 root root  4096 Mar  1  2021 .vscode
drwxr-xr-x  3 root root  4096 Aug  9 10:19 .wpscan
-rw-------  1 root root    98 Oct 24 16:13 .Xauthority
-rw-------  1 root root 27650 Oct 24 18:12 .xsession-errors
-rw-------  1 root root 40368 Oct 24 12:32 .xsession-errors.old
-rw-------  1 root root 24328 Oct 24 17:07 .zsh_history
-rw-r--r--  1 root root  8238 Feb 27  2021 .zshrc

I need to store this output data in a text file. Please help me.

2 answers

  • answered 2021-10-24 13:05 js-on

    os.system("ls -al") won't return the output you normally see in the shell but only the return code. 0 if the command was executed successfully, 1 if not, etc. Read more about this here.

    But you can use subprocess.check_output()to do so. Be aware, that the command must be passed to the method as a list of commands / parameters:

    import subprocess
    output = subprocess.check_output(["ls", "-al"])
    open("output.txt", "w").write(output)
    

  • answered 2021-10-24 13:06 Xnero

    You can use > to write the command line output to a file as follows:

    import os
    os.system('ls -al > output.txt')
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum