Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

shell

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)
like image 432
BoJack Horseman Avatar asked Dec 11 '22 09:12

BoJack Horseman


2 Answers

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_)
like image 77
Raydel Miranda Avatar answered Mar 23 '23 08:03

Raydel Miranda


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.

like image 40
Oliver Matthews Avatar answered Mar 23 '23 08:03

Oliver Matthews