Python 3评估字符串

时间:2016-06-22 15:37:09

标签: python python-3.x

自我承认PHP编码器转向Python方面,我的头疼。我试图做我认为简单的事情。读入一个文件(使其工作),然后将每行输入存储到一个变量中,然后将字符串变量计算为现有的文本字符串。

以下是我所拥有的:

with open('./users.txt') as users:
    for user in users:
        conn.request("GET", "/vmrest/users?query=(alias%2520is%2520{})".format(user), headers)
        res = conn.getresponse()
        data = res.read()

我想要的只是将我的用户变量中的值放在字符串末尾" / vmrest / users?query =(alias%2520is%2520 user variable here&#34 ;,标题)

由于

修改 意识到我并没有包含对不起发生的事情。以下是我在执行时得到的反馈。

Traceback (most recent call last):
File "/opt/rh/rh-python35/root/usr/lib64/python3.5/http/client.py", line 885, in send
 self.sock.sendall(data)
File "/opt/rh/rh-python35/root/usr/lib64/python3.5/ssl.py", line 886, in sendall
v = self.send(data[count:])
TypeError: unhashable type: 'slice'

在处理上述异常期间,发生了另一个异常:

Traceback (most recent call last):
File "amer-unity.py", line 12, in <module>
conn.request("GET", "/vmrest/users?query=(alias%2520is%2520{})".format(user), headers)
File "/opt/rh/rh-python35/root/usr/lib64/python3.5/http/client.py", line 1083, in request
self._send_request(method, url, body, headers)
File "/opt/rh/rh-python35/root/usr/lib64/python3.5/http/client.py", line 1128, in _send_request
self.endheaders(body)
File "/opt/rh/rh-python35/root/usr/lib64/python3.5/http/client.py", line 1079, in endheaders
self._send_output(message_body)
File "/opt/rh/rh-python35/root/usr/lib64/python3.5/http/client.py", line 913, in _send_output
self.send(message_body)
File "/opt/rh/rh-python35/root/usr/lib64/python3.5/http/client.py", line 889, in send
self.sock.sendall(d)
File "/opt/rh/rh-python35/root/usr/lib64/python3.5/ssl.py", line 886, in sendall
v = self.send(data[count:])
File "/opt/rh/rh-python35/root/usr/lib64/python3.5/ssl.py", line 856, in send
return self._sslobj.write(data)
File "/opt/rh/rh-python35/root/usr/lib64/python3.5/ssl.py", line 581, in write
return self._sslobj.write(data)
TypeError: a bytes-like object is required, not 'str'

1 个答案:

答案 0 :(得分:1)

首先,正如@acushner建议的那样,你应该strip你的行:

"/vmrest/users?query=(alias%2520is%2520{})".format(user.strip())

这将从user字符串中删除任何前导或尾随空格。请记住,在Python中,当您阅读文件的行时,它包含行终止符(可能'\n',因为您在* nix上)。这将确保它被删除。

您可能还想跳过空行:

user = user.strip()
if user:
    conn.request("GET", "/vmrest/users?query=(alias%2520is%2520{})".format(user), headers)
    # ...

如果没有解决问题,我强烈建议您切换到requests。它是一个更简单的库,用于发送Web请求和接收响应。它通常&#34;只是工作&#34;没有太大惊小怪。它是第三方,因此您需要先安装它:

pip install requests

然后你会像这样使用它:

import requests

# ... some other code ...

with open('./users.txt') as users:
    for user in users:
        user = user.strip()
        if user:
            res = requests.get("/vmrest/users?query=(alias%2520is%2520{})".format(user.strip()), headers=headers)
            data = res.text

请注意,建立连接的设置代码为零;你只需要调用模块方法。它还有一些额外的细节,比如解析JSON:

data = res.json()