4

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)
1
  • I like to point out the subprocess documentation helped me get it working before. They are well written and worth your time. docs.python.org/2.7/library/… Commented Dec 6, 2013 at 11:58

2 Answers 2

13

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_)
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Popen also allow you get the output. Even, directly to a file you have opened.
Like its name implies, check_output will check that the command succeeded. This is often what you want, but many commands (like diff or grep for example) will signal an error even though the command performed exactly the job you requested -- diff returns nonzero when there were differences (so basically always when it does something useful); grep will fail if there were no matches. You need to understand when this matters; way too many questions here are from people who blindly followed a suggestion like this, and then didn't know how to cope with the consequences.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.