Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am trying to write my below pinging script results into the Text file, but I am getting an error message.

Below is my code:

import os

import time

import subprocess

# Open file for saving ping results

results_file = open("results.txt", "w")

with open('ip-source.txt') as IPs:

    hosts = IPs.read()

    hosts = hosts.splitlines()

    for ip in hosts:

        os.system('cls')

        print('Printing now:', ip)

        print('-'*60)

        result = os.system('ping -n 4 {}'.format(ip))

        print('-'*60)

        time.sleep(1)

with open("output.txt", "w", encoding="utf8") as output:

    output.write("\n".join([post.text for post in result]))

and when i ran it i got below error message:

Traceback (most recent call last):

File "script.py", line 21, in <module>

output.write("\n".join([post.text for post in result]))

Error:

TypeError: 'int' object is not iterable

1 Answer

0 votes
by (36.8k points)
edited by

The os.system returns an exit signal (typically 0 or 1) from a process called. If you look, os.system is just the wrapper function for subprocess.Popen.

You need to use something like a subprocess. Popen or subprocess.check_output and then b) add results to the list:

import subprocess

...

results = []

for ip in hosts:

    ...

    results.append(str(subprocess.check_output(["ping", "-n", "4", str(ip)])))

with open("output.txt", "w", encoding="utf8") as output:

    output.writelines(results)

 If you are a beginner and want to know more about Python the do check out the python for data science course

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...