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

时间:2019-08-09 16:08:48

标签: python python-3.x python-requests subprocess sys

它以多种方式混乱

代码如下:

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无效,但由于某种原因,它正在做这件奇怪的事

1 个答案:

答案 0 :(得分:0)

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

ip = sys.argv[1]

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

如果您使用的是os.system,则无需执行subprocess。代替:

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

您可以这样做:

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

并且当ip = 55时,ipVerification的值是:

connect: Invalid argument

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

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