[英]Python: eval string with \n at the end
How can I perform a eval on a string with \\n ? 如何使用\\ n对字符串进行评估?
Why does this not work? 为什么这不起作用?
a = eval('"hello \n"')
In [70]: eval("\"hello \n\"")
File "<string>", line 1
"hello
^
SyntaxError: EOL while scanning string literal
Whereas this does 鉴于
a = "hello \n"
My use case is that a script executed through subprocess is outputing a dictionary as a string of which I am capturing the stdout of it and I would like to perform an eval on it. 我的用例是通过子进程执行的脚本将字典输出为字符串,我正在捕获字典的标准输出,并且希望对其进行评估。
'''[
{ "hello": "the description of this is\' \n"}
]'''
You need to escape the backslash. 您需要转义反斜杠。
>>> eval('"hello \n"')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
"hello
^
SyntaxError: EOL while scanning string literal
>>> eval('"hello \\n"')
'hello \n'
>>> print(eval('"hello \\n"'))
hello
>>>
Without that escape, Python will see this code (which is an obvious error): 没有该转义,Python将看到以下代码(这是一个明显的错误):
"hello
"
Rather than the desired code: 而不是所需的代码:
"hello \n"
If you want to specify a string that has a literal \\
and n
in it you either need to double the backslash, or use a raw string literal: 如果要指定一个包含文字
\\
和n
的字符串,则需要将反斜杠加倍,或者使用原始字符串文字:
>>> '"hello\\n"'
'"hello\\n"'
>>> r'"hello\n"'
'"hello\\n"'
Such a string can then be evaluated as a Python expression containing a string literal: 然后可以将这样的字符串评估为包含字符串文字的Python表达式:
>>> eval(r'"hello\n"')
'hello\n'
If your output is produced by a child process outputting the value with pprint.pprint()
, you are doing more than just read that stream, as that produces perfectly valid Python syntax. 如果您的输出是由子进程使用
pprint.pprint()
输出值产生的,则您所做的不仅仅是读取该流,因为这会产生完全有效的Python语法。 Don't copy and paste that output into a Python interpreter, for example, because that'll just interpret the escape sequences directly (so before you pass it to eval()
). 例如,请勿将输出复制并粘贴到Python解释器中,因为这将直接解释转义序列(因此,在将其传递给
eval()
)。 If you are developing in an interpreter, you could use pprint.pformat()
to produce a variable with the output, rather than write to stdout. 如果您正在使用解释器进行开发,则可以使用
pprint.pformat()
来生成带有输出的变量,而不是写入stdout。
If you are trying to use Python repr()
or pprint.pprint()
output to pass data between systems, however, stop right there. 但是,如果您尝试使用Python
repr()
或pprint.pprint()
输出在系统之间传递数据,请在此处停止。 Use a proper serialisation format instead, such as JSON. 请改用正确的序列化格式,例如JSON。 If that's not an option, at the very least use
ast.literal_eval()
to limit what your code accepts to only Python literals, and not arbitrary code (such as '__import__("os").system("rm -rf /")
). 如果这不是一个选择,请至少使用
ast.literal_eval()
将您的代码接受的内容限制为仅 Python文字,而不是任意代码(例如'__import__("os").system("rm -rf /")
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.