开发者

reading info from text file and passing read lines to urlencode python function

I'm trying to send urlencode() data to my web server. The data used for the urlencode() function is read from a text file located on my local machine. When I read the input data for the urlencode() function from the .py script no error is being thrown. However, if the input data for the urlencode() function is comming from a local input text file I get the following error:

Traceback (most recent call last): File "active_directory_ssl_test.py", line 30, in params = urllib.urlencode(dict(LINE)) ValueError: dictionary update sequence element #0 has length 1; 2 is required

I'm doing the following:

FILE=open(IN_FILE, 'r')
LINE = FILE.readline()
while LINE:
    print LINE
    LINE = FILE.readline()
    params = urllib.urlencode(dict(LINE))
    try:
        f_handler = urlopen('https://host_name/path_name/file_name', params)

Why is there a difference, an error, when reading data from a text file. In both cases a variable is used as a parameter to the urlencode() function.

This is the content of the input text file:

{'hostname' : 'host.1.com', 'port' : '389', 'basedn' : 'CN=Users,DC=prem,DC=local', 'username' : 'CN=Administrat开发者_开发问答or,CN=Users,DC=onprem,DC=local', 'password' : 'passwd', 'roupname' : 'CN=Group,CN=Users,DC=onprem,DC=local', 'attribute' : 'name', 'enabled' : 'sync', 'impsync' : 'sync', 'enabled' : 'enabled', 'username' : 'user@1.com', 'password' : 'passwd', 'update' ; 'update'}


I'll go ahead and post my comment as an answer, as it is the answer. You're calling dict() on a string. The dict() function expects one of two types of input. Either A. a list of tuples that form (key, value) pairs, or B. keyword arguments that come in the form key = value. You're not passing either of those.

-- Extra detail for the Comments --

>>> input = {'key1': 'value1', 'key2': 'value2'}
>>> type(input)
<type 'dict'>
>>> dict(input)
{'key2': 'value2', 'key1': 'value1'}
>>> input = "{'key1': 'value1', 'key2': 'value2'}" # This is your 2nd form.
>>> type(input)
<type 'str'>
>>> dict(input)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required

Also, for what it's worth, in your first example the call to dict() is superfluous. You already have a dictionary which was declared using literal syntax.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜