user6367569 user6367569 - 2 months ago 9
Python Question

pinging websites from array in a loop

import subproccess
import sys

mylist= ['google.com','bbc.com','yahoo.com','gmail.com','hotmail.com',
'amazon.com']

for ping in mylist(0,5):
result = os.system("ping %s" % ping)
result.stdout=open("test.txt","w")
result.stdout.close()


Can someone please find the mistake in my code? I want to call this script from cmd terminal. The aim of this code is to ping each of the website every time and then write the result in a text file. I'm quite new with python and I don't know how to build a proper code.

Answer
  • os not imported
  • mylist = ['google.com','bbc.com','yahoo.com','gmail.com','hotmail.com','amazon.com']
  • for ping in mylist:
  • result = os.system("ping -c 1 %s" % ping)
  • f = open("test.txt","w") (open the file before entering the loop, else it would rewrite the file everytime the loop iterates)

    import os
    
    mylist= ['google.com','bbc.com','yahoo.com','gmail.com','hotmail.com',
             'amazon.com']
    
    f = open("file.txt", 'w')
    for ping in mylist:
        result = os.system("ping -c 1 %s" % ping)
        f.write(ping + " : " +result + "\n")
    f.close()
    
Comments