簡體   English   中英

為什么RestrictedPython在與Python 3.6一起使用時表現不同?

[英]Why does RestrictedPython behave differently when used with Python 3.6?

我正在嘗試使用Python 3.6 RestrictedPython (請參閱文檔 )。 以下代碼在Python 2.73.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM