python - 如何在 Python 中使用 exec() 换行?

标签 python python-3.x python-requests newline

我有一个网站,只发送几行 Python 代码。我使用请求连接到此站点并获取它,但其中有\n 。这是我的意思的一个例子:

import requests
r = r.get("www.example.com")
t = r.text
exec(t)

变量 t 有新行。这是错误:

>>> exec(t)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    import time\nprint(time.time())
                              ^
SyntaxError: unexpected character after line continuation character

另一件事:在检索它的网页上,它是一个\n,但 t 的值是\n 而不是\n。我不确定我能做些什么来解决这个问题。

最佳答案

如果您的字符串实际上包含换行符,那么这会很好地工作。您从服务器返回的字符串甚至不包含换行符 - 它实际上包含“\n”。请参阅下面的示例来演示这一点:

>>> t = 'import time\\nprint(time.time())'
>>> exec(t)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    import time\nprint(time.time())
                                  ^
SyntaxError: unexpected character after line continuation character
>>> t = 'import time\nprint(time.time())'
>>> exec(t)
1491841224.27

请注意第一行如何包含文字“\n”,而第二次定义t时,我实际上使用了真正的换行符。在第一个示例中,它给出了与您得到的完全相同的错误,使我相信这就是您的问题。

因此,要解决此问题,您要么必须修改服务器(因为您声称这是您的网站)以返回带有实际换行符的数据,要么,如果您不想(或不能)修改服务器,您必须将“\n”替换为实际的换行符或分号。一种方法是 t.replace('\\n', '\n')。因此,如果您决定以这种迂回方式修复它,您的代码将如下所示:

import requests
r = r.get("www.example.com")
t = r.text
exec(t.replace('\\n', '\n'))

但是,如果您修复了该网站,您的代码可能看起来与您的问题中的代码完全相同并且可以正常工作。

关于python - 如何在 Python 中使用 exec() 换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43328160/

相关文章:

python - 使用 apt_pkg 以编程方式安装 debian 软件包时出错

python - 使用 numpy/scipy 的快速 b 样条算法

python - 在函数内部使用全局变量

Python 请求 : Stream iter_content chunks into a pandas read_csv function

javascript - 如何使用 requests_html 忽略无效的 SSL 证书?

python - 为什么 python 的 datetime.isocalendar() 和 datetime.year 不同?

Python 2 中的 Python 3 f-string 替代品

python - Python 中的双向链表

python-3.x - 在Windows上安装geograpy3

python - 来自 pogdesign.co.uk/cat/的数据抓取