我将如何使用错误的输出修复此脚本?

How would I fix this script with the wrong output?

它以多种方式搞砸了

代码如下:

import threading
import sys
import time
import os
import subprocess
import requests
import threading

ip = sys.argv[1:]

website_loaded = False

def verify():
    while website_loaded == False:
        sys.stdout.write("Verifying IP    \r")
        time.sleep(0.5)
        sys.stdout.write("Verifying IP.   \r")
        time.sleep(0.5)
        sys.stdout.write("Verifying IP..  \r")
        time.sleep(0.5)
        sys.stdout.write("Verifying IP... \r")
        time.sleep(0.5)
        continue

verify_thread = threading.Thread(target = verify, args = ())
verify_thread.start()

ping = os.system("ping %s >nul" % str(ip))
ipVerification = subprocess.getoutput(str(ping))

website_loaded = True
if ipVerification == "Ping request could not find host %s. Please check the name and try again." % ip:
    print("Invalid IP. Please try again")
    print("Press any key to exit")
    os.system("pause >nul")
    exit()
elif ipVerification.find('PING: transmit failed. General failure.') != -1:
    print("Invalid IP. Please try again")
    print("Press any key to exit")
    os.system("pause >nul")
    exit()
website_loaded = False

def loading():
    while website_loaded == False:
        sys.stdout.write("Loading    \r")
        time.sleep(0.5)
        sys.stdout.write("Loading.   \r")
        time.sleep(0.5)
        sys.stdout.write("Loading..  \r")
        time.sleep(0.5)
        sys.stdout.write("Loading... \r")
        time.sleep(0.5)
        continue

loading_thread = threading.Thread(target = loading, args = ())
loading_thread.start()

info = requests.get("http://ip-api.com/json/%s" % ip).json()

website_loaded = True

print(info)

当我在 cmd 中键入 "ipinfo.py 55" 时,输出为“{'message': 'invalid query', 'query': '[]', 'status': 'fail'} 正在加载... P...”,我不知道为什么。我希望它说 IP 无效,但出于某种原因它正在做这件奇怪的事情

要获取单个 IP,请执行以下操作:

ip = sys.argv[1]

如果您想要正确的命令行处理,请查看 argparse

如果您使用 subprocess,则无需执行 os.system。而不是:

ping = os.system("ping %s >nul" % str(ip))
ipVerification = subprocess.getoutput(str(ping))

你可以这样做:

ipVerification = subprocess.getoutput(f"ping {ip}")

ip = 55ipVerification 的值是:

connect: Invalid argument

这将允许您在调用 ip-api.com API 之前捕获它。或者,您可以忽略 ping 并让来自 ip-api.com 的响应中的 message 确定 IP 地址是否有效。

if response.get("message") == "invalid query":
    print(f"The IP address is invalid: {ip}".
else:
    print(response.get("isp"))