【发布时间】:2013-04-14 22:20:32
【问题描述】:
我需要能够从字符串中运行大量 python 代码。简单地使用exec 似乎不起作用,因为虽然代码在正常设置下完美运行,但这样做似乎会引发错误。我也不认为我可以将它导入它,因为它托管在互联网上。代码如下:
import urllib.request
URL = "https://dl.dropboxusercontent.com/u/127476718/instructions.txt"
def main():
instructions = urllib.request.urlopen(URL)
exec(instructions.read().decode())
if __name__ == "__main__":
main()
这是我遇到的错误:
Traceback (most recent call last):
File "C:\Python33\rc.py", line 12, in <module>
main()
File "C:\Python33\rc.py", line 9, in main
exec(instructions.read().decode())
File "<string>", line 144, in <module>
File "<string>", line 120, in main
NameError: global name 'Player' is not defined
我尝试运行的代码可在第一个代码 sn-p 中的链接中找到。
如果您有任何问题,我会回答。谢谢。
【问题讨论】:
-
您可能需要考虑一下这种设计的安全隐患。
-
就 NPE 而言,考虑 PyPy 的 sandboxing 功能可能会很有用。
-
补充 NPE 的观点,请注意 urllib 文档中的这一点:
When opening HTTPS URLs, it does not attempt to validate the server certificate. Use at your own risk!换句话说,中间人攻击是可能的,这种设计将允许攻击者执行任意代码在您的系统上。 -
考虑到我打算使用它的方式是编写它链接到我自己的代码,将其托管在保管箱上并将此代码作为可执行文件提供,这仍然是一个问题。 (从而使更新代码更容易)。
-
应该可以的。你遇到了什么错误?
标签: python url python-3.x exec dropbox