![](/img/trans.png)
[英]In Python 3.x, why does os.chdir() behave differently when used with os.listdir() and os.scandir() ? (Python 3.9.7)
[英]Why does RestrictedPython behave differently when used with Python 3.6?
我正在尝试使用Python 3.6
RestrictedPython (请参阅文档 )。 以下代码在Python 2.7
和3.6
产生不同的结果:
from RestrictedPython import compile_restricted
from RestrictedPython.Guards import safe_builtins
restricted_globals = dict(__builtins__ = safe_builtins)
src = '''
open('/etc/passwd')
'''
code = compile_restricted(src, '<string>', 'exec')
exec(code) in restricted_globals
在Python 2.7
,结果如预期:
Traceback (most recent call last):
File "...Playground.py", line 10, in <module>
exec(code) in restricted_globals
File "<string>", line 2, in <module>
NameError: name 'open' is not defined
但是在Python 3.6
,结果是:
Traceback (most recent call last):
File "...Playground.py", line 10, in <module>
exec(code) in restricted_globals
File "<string>", line 2, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '/etc/passwd'
现在显然已知open
名称/方法,但情况并非如此。 为什么这个代码在3.6
使用时的行为与在2.7
使用时的行为不同?
您应该为3.6版编写代码的方式如下所示:
https://github.com/zopefoundation/RestrictedPython
在“有问题的代码示例”下。
即,以下代码将起作用,即open将不定义:
from RestrictedPython import compile_restricted
from RestrictedPython import safe_builtins
source_code = """
open('/etc/passwd')
"""
byte_code = compile_restricted(source_code, '<inline>', 'exec')
exec(byte_code, {'__builtins__': safe_builtins}, {})
至于发生这种情况的原因,我没有,但我想提出一种让它无论如何都能运作的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.