I use Python2.7. You need to convert str-> dict and the ast.literal_eval command does a good job, but only in the terminal:

$python >>>import ast >>>s = '{...}' #str type >>>d = ast.literal_eval(s) #dict type 

When I add this script to the program, magic happens and it stops working. It looks like this:

 result = re.recognize_by_file(inputFile, X) result_dict = ast.literal_eval(result) 

Here when you add this code - the error takes off:

 File "<string>", line 0 ^ SyntaxError: unexpected EOF while parsing 

I read that the problem may be in the Python version, but there is no possibility to change it. Type inference and an example of the result string itself:

 print(result) 

{"status": {"msg": "No result", "code": 1001, "version": "1.0"}}

 print(type(result)) 

type 'str'

 result_dict = ast.literal_eval(result) #Ну дальше типы я не могу выводить, потому что вылетает ошибка. 

The full output looks like this:

  Traceback (most recent call last): File "/home/maxlager/PyCharm_Projects/BOT_2.7/bot.py", line 42, in <module> bot.polling(none_stop=True, interval=0) File "/home/maxlager/.local/lib/python2.7/site-packages/telebot/__init__.py", line 183, in polling self.__threaded_polling(none_stop, interval, timeout) File "/home/maxlager/.local/lib/python2.7/site-packages/telebot/__init__.py", line 207, in __threaded_polling self.worker_pool.raise_exceptions() File "/home/maxlager/.local/lib/python2.7/site-packages/telebot/util.py", line 103, in raise_exceptions six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2]) File "/home/maxlager/.local/lib/python2.7/site-packages/telebot/util.py", line 54, in run task(*args, **kwargs) File "/home/maxlager/PyCharm_Projects/BOT_2.7/bot.py", line 38, in handler_text result_dict = ast.literal_eval(result) File "/usr/lib/python2.7/ast.py", line 49, in literal_eval node_or_string = parse(node_or_string, mode='eval') File "/usr/lib/python2.7/ast.py", line 37, in parse return compile(source, filename, mode, PyCF_ONLY_AST) File "<unknown>", line 0 ^ 

SyntaxError: unexpected EOF while parsing

42 line looks like this:

  bot.polling(none_stop=True, interval=0) 
  • one
    Here you need to use json.loads - andreymal

1 answer 1

In Python, source code padding has the meaning:

 >>> import ast >>> ast.literal_eval('""\n') '' >>> ast.literal_eval('""\n ') Traceback (most recent call last): ... return compile(source, filename, mode, PyCF_ONLY_AST) File "<unknown>", line 2 ^ SyntaxError: unexpected EOF while parsing 

On the last line there is an unexpected indent. The error is an artifact of the implementation of ast.literal_eval() (a possible bug, since for recognition of constants, spaces at the end should not have a value — the result is one value, not a set of instructions). You can bypass this behavior with .rstrip() .

In your case, it's better to json.loads() as @andreymal recommended .