求助:编写支持选择站点/自定义URL的Python Ping脚本
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 (-nfor Windows,-cfor 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:
- Save the code as
ping_tool.py - Run it with
python ping_tool.py - Follow the on-screen prompts to select your ping target
内容的提问来源于stack exchange,提问作者Jake
相关产品推荐
相关产品推荐

