i从命令行执行将参数传递给URL,但由于无效连接而引发错误

问题描述 投票:0回答:1

URL的主机值将作为参数传递,但是当我打印URL时,它可以正常工作,但不能作为整个脚本正常执行。

Python脚本:

import requests
import json
import urllib
import sys 
import os

host=(str(sys.argv[1]))

headers={
        "accept": "application/json",
        "content-type": "application/json"
    }

test_urls = 'https://{host}/Thingworx/Things/PG.MonitorStats.Stream/Services/GetStreamData?maxItems=1&oldesFirst=false&appKey=0b858f3f-4ed0-499c-a4d2-9ad0fbc0da9b&method=post'.format(host=host)
print (test_urls)

def return_json(url):
    try:
        response = requests.get(url,headers=headers)

        # Consider any status other than 2xx an error
        if not response.status_code // 100 == 2:
            return "Error: Unexpected response {}".format(response)

        json_obj = response.json()
        return json.dumps(json_obj)
    except requests.exceptions.RequestException as e:
        # A serious problem happened, like an SSLError or InvalidURL
        return "Error: {}".format(e)

for url in test_urls:
    print return_json(url).format(host=host)

错误输出:

Error: Invalid URL 'h': No schema supplied. Perhaps you meant http://h?
Error: No connection adapters were found for ':'
Error: Invalid URL '/': No schema supplied. Perhaps you meant http:///?
python url python-requests
1个回答
1
投票

[test_urls是一个字符串(不是字符串数组),因此您要遍历每个字符并尝试先获取h,然后依次为t,然后依次为t,...

并且format的输出上的return_json没有意义。您的print也没有(假设您使用的是Python 3,则print是一个函数)。

也请求具有用于“将2xx以外的其他状态视为错误”的快捷方式:Response.okResponse.ok

而且...为什么要转储JSON响应?如果需要文本版本,只需返回Response.raise_for_status(),就没有理由解码,然后立即重新编码响应。

© www.soinside.com 2019 - 2024. All rights reserved.