Ping a site in Python?

前端 未结 15 2563
我寻月下人不归
我寻月下人不归 2020-11-22 09:22

How do I ping a website or IP address with Python?

15条回答
  •  野性不改
    2020-11-22 09:56

    Here's a short snippet using subprocess. The check_call method either returns 0 for success, or raises an exception. This way, I don't have to parse the output of ping. I'm using shlex to split the command line arguments.

      import subprocess
      import shlex
    
      command_line = "ping -c 1 www.google.comsldjkflksj"
      args = shlex.split(command_line)
      try:
          subprocess.check_call(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
          print "Website is there."
      except subprocess.CalledProcessError:
          print "Couldn't get a ping."
    

提交回复
热议问题