Class 4 Lab 5 ‐ OS Module & Open Function - Justin-Boyd/Python-Class GitHub Wiki

Step 1

  • Create a new Python file in PyCharm by right-clicking the project you created and selecting New > Python File.

Step 2

  • Create a variable and assign it a filename value provided by the user.
file_name = input("Choose a filename: ")

Step 3

  • Import the OS library
import os

Step 4

  • Use the os.system() function to ping the public IP address 8.8.8.8
#for mac and linux add -c 4 flag
os.system(r"ping 8.8.8.8")

Step 5

  • Save the results to a new file with the name chosen by the user.
  • Note: Since the os.system() function executes commands on the operating system, you need to rely on stdout operations, such as output redirects, to create and append to a file using the symbol >>. In addition, remember that internet connectivity can be validated by pinging a public IP address.
os.system(r'ping 8.8.8.8 >> "' + file_name + '".txt"')

Step 6

  • Use the open() function to read the file that was created in the previous step.
with open(file_name + ".txt","r") as file:

Step 7

  • Create an if condition to check if the file contains “ms.”
if "ms" in file.read():

Step 8

  • Print a message to inform the user that internet connectivity is available.
  • Note: Observe the output of the ping command when an IP address is reachable, as opposed to when it is unreachable. Each outcome will output a string that can be used in the code to create a condition statement.
print("You have an internet connection")

Step 9

  • Add an else statement to print a message if there is no internet connection.
else:
    print("You don't have an internet connection")

Step 10

  • Open the file and view the result of the ping.

Final Code

import os

file_name = input("Choose a filename: ")
#for mac and linux add -c 4 flag
os.system(r'ping 8.8.8.8 >> "' + file_name + '".txt"')
with open(file_name + ".txt","r") as file:
    if "ms" in file.read():
        print("You have an internet connection")
    else:
        print("You don't have an internet connection")