You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:编写支持选择站点/自定义URL的Python Ping脚本

Python Ping Menu Script

Got it, let's put together that Python script you need! This implementation gives you a simple, interactive menu to ping Google, Yahoo, or a custom URL, and it works smoothly across Windows, macOS, and Linux.

import os
import platform

def ping_host(host):
    # Handle cross-platform ping command differences
    ping_param = '-n' if platform.system().lower() == 'windows' else '-c'
    # Build and run the ping command (sends 4 packets by default)
    command = f'ping {ping_param} 4 {host}'
    os.system(command)

def main():
    while True:
        print("\n=== Ping Tool Menu ===")
        print("1. Ping Google")
        print("2. Ping Yahoo")
        print("3. Enter Custom URL/IP")
        print("4. Exit")
        
        user_choice = input("Pick an option (1-4): ")
        
        if user_choice == '1':
            print("\nPinging Google...")
            ping_host('google.com')
        elif user_choice == '2':
            print("\nPinging Yahoo...")
            ping_host('yahoo.com')
        elif user_choice == '3':
            custom_target = input("Type the URL or IP address to ping: ")
            print(f"\nPinging {custom_target}...")
            ping_host(custom_target)
        elif user_choice == '4':
            print("Closing the tool. Catch you later!")
            break
        else:
            print("Oops, that's not a valid option. Please enter a number between 1 and 4.")

if __name__ == "__main__":
    main()

Quick Breakdown of the Script:

  • Cross-platform compatibility: Uses platform.system() to detect your OS, then uses the correct ping command flag (-n for Windows, -c for macOS/Linux) so it works everywhere.
  • Loopable menu: The script stays open until you choose to exit, so you can run multiple pings without restarting the program.
  • User-friendly feedback: Prints clear messages before each ping so you know exactly what's running.
  • Basic input validation: Catches invalid menu selections and prompts you to try again.

To use it:

  1. Save the code as ping_tool.py
  2. Run it with python ping_tool.py
  3. Follow the on-screen prompts to select your ping target

内容的提问来源于stack exchange,提问作者Jake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 06:43:06