python Save the output of a shell command into a text file

16,945

Solution 1

Try something like this:

import subprocess
file_ = open("ouput.txt", "w")
subprocess.Popen("ls", stdout=file_)

EDIT: Matching your needs

import subprocess

file_ = open("ouput.txt", "w")
subprocess.Popen(["host", ipAddress], stdout=file_)

Solution 2

Use subprocess.check_output instead of Popen That will give you a string back containing the output, which you can then write out to the file.

Share:
16,945

Related videos on Youtube

BoJack Horseman
Author by

BoJack Horseman

I need to go take a shower so I can't tell if I'm crying or not

Updated on September 26, 2022

Comments

  • BoJack Horseman
    BoJack Horseman over 1 year

    I want to save the output of a shell command into a textfile via python. This is my actual, pretty basic python code:

    Edit here is the final script, thank you for your help :)

    import subprocess
    
    ip_adress_4 = 0    
    pr = open("pointer_record.txt", "w")
    
    while (ip_adress_4 < 255):
        ip_adress_4 = ip_adress_4 + 1
        ip_adress = '82.198.205.%d' % (ip_adress_4,)
        subprocess.Popen("host %s" % ip_adress, stdout=pr, shell=True)
    
  • Raydel Miranda
    Raydel Miranda over 10 years
    Popen also allow you get the output. Even, directly to a file you have opened.