Search code examples
pythonsocketsipip-addresstraceback

Multiple Traceback (most recent call last) and FIleNotFoundError when trying to ping google.com


I am trying to make a program for pinging ip adresses etc. However every time i try to ping an Ip address i always get multiple errors. I have tried multiple different ways to ping an ip address and non of them work. Any help would be greatly appreciated! :D

My code:

import time
import socket
import os
import subprocess

time.sleep(1)

print('    _  __        __')
time.sleep(0.3)
print('  / |/ /__  ___/ /__')
time.sleep(0.3)
print(' /    / _ \/ _  / -_)')
time.sleep(0.3)
print('/_/|_/\___/\_,_/\__/')

print('\n\n')

time.sleep(1)

while True:
    prompt = input('>>> ')

    if prompt == '/ip-?':
        print(socket.gethostbyname(socket.getfqdn()))
    elif prompt == '/hn-?':
        print(socket.gethostname())
    elif prompt == '/h':
        print('\n/ip-? --- IP ADDRESS')
        print('/hn-? --- HOST NAME')
        print('/e --- EXIT')
        print('\n')
    elif prompt == '/ip->':
        #THIS IS WHERE THE PROBLEM IS OCCURING
        out = subprocess.run(['ping', 'google.com'], capture_output=True)
        print(out.stdout.decode())
    elif prompt == '/e':
        break

Traceback:

Traceback (most recent call last):
  File "D:\PYTHON\PROJECTS\everything.py", line 33, in <module>
    out = subprocess.run(['ping', 'google.com'], capture_output=True)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\subprocess.py", line 489, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\subprocess.py", line 1307, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

Solution

  • ping.exe should be in the system directory C:\WindowsSystem32. If it fails to run without the path, add it. You can use forward slashes to avoid potential problems with python's use of \ to escape special characters.

    out = subprocess.run(['C:/Windows/System32/ping', 'google.com'], capture_output=True)
    

    Note that this makes your program windows only. Linux/Mac have "ping" programs also, so you could make this a fallback if a simple "ping" doesn't work. The "ping" program may have different parameters and outputs depending on platform, so you may need to check platform version first, and implement two different versions of your code.