Why does RestrictedPython behave differently when used with Python 3.6? - python

I'm trying to use RestrictedPython(see documentation) with Python 3.6.
The following code yields different results in Python 2.7 and in 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
In Python 2.7, the result is as expected:
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
But in Python 3.6, the results is:
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'
The open name/method is now obviously known, which should not be the case. Why does this code behave different when used in 3.6 than when used in 2.7?

The way you should write your code for version 3.6 is presented here:
https://github.com/zopefoundation/RestrictedPython
Under "Problematic Code Example".
Namely, the following code will work, that is, open will be not defined:
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}, {})
As for the reason why this happens, I don't have one, but I wanted to present a way of making it work anyways.

Related

How can I run many python scripts at once?

I'm working on some python scripts using PyCharm. Running scripts from PyCharm works fine, but I tried bundling them up with a batch file and cmd just goes nuts:
C:\Users\White Python\Desktop\Fran\theconfluence\graphs\leaderboard>python htmlcreator.py
Traceback (most recent call last):
File "htmlcreator.py", line 4, in <module>
w = open(str(Path(__file__).parents[2]) + "/week.txt", "r")
File "C:\Users\White Python\AppData\Local\Programs\Python\Python38-32\lib\pathlib.py", line 617, in __getitem__
raise IndexError(idx)
IndexError: 2
C:\Users\White Python\Desktop\Fran\theconfluence\graphs\leaderboard>cd ..\retention
C:\Users\White Python\Desktop\Fran\theconfluence\graphs\retention>python creategraph.py
['C:\\Users\\White Python\\Desktop\\Fran\\theconfluence\\graphs\\retention', 'C:\\Users\\White Python\\AppData\\Local\\Programs\\Python
\\Python38-32\\python38.zip', 'C:\\Users\\White Python\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\White Python\
\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\White Python\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Us
ers\\White Python\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages']
Traceback (most recent call last):
File "creategraph.py", line 9, in <module>
w = open(str(Path(__file__).parents[2]) + "/week.txt", "r")
File "C:\Users\White Python\AppData\Local\Programs\Python\Python38-32\lib\pathlib.py", line 617, in __getitem__
raise IndexError(idx)
IndexError: 2
Other scripts which did not require importing modules worked fine. Help!
Is your html creator a script? Or more like module? If it's like a module the try:
python -m htmlcreator

python reload module for beginner. importlib.reload doesn't seem to work

I have a file called skdb and class called skmysqldb. I am trying to force reload.
I tried reloading "skdb", "skdb.skmysqldb" "skmysqldb" and none of them seem to work.
>>> from skdb import skmysqldb
>>> importlib.reload(skdb.skmysqldb)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'skdb' is not defined
>>> importlib.reload(skmysqldb)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\importlib\__init__.py", line 139, in reload
raise TypeError("reload() argument must be a module")
TypeError: reload() argument must be a module
>>> importlib.reload(skdb)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'skdb' is not defined
When you import some object using the from <module> import <obj> syntax as in
from skdb import skmysqldb
the module itself is not added to the current namespace, hence why you get a NameError when you try to do reload(skdb).
Instead try:
import skdb
importlib.reload(skdb)
Be cautious when using reload. If the module your reload imports other modules, those modules are not reloaded recursively, so depending on the exact code you can wind up in a rather broken state where it's better to just restart the whole interpreter.
I don't think this is supported, but try doing del sys.modules['mymodule'] for everything that vaguely matches. To find relevant ones, try something like [x for x in sys.modules if 'mymodule' in x].

IndexError when trying to execute a Script

I'm trying to figure out why this
def scanner(fileName, function):
with open(fileName) as file:
for line in file:
function(line)
def toSmallLetters(line):
print line.lower()
def paramin(fileName):
scanner(fileName, toSmallLetters)
if __name__ == "__main__":
import sys
paramin(sys.argv[1])
throws this error:
Traceback (most recent call last):
File "script.py", line 14, in <module>
paramin(sys.argv[1])
IndexError: list index out of range
What's wrong?
You are getting:
Traceback (most recent call last):
File "script.py", line 14, in <module>
paramin(sys.argv[1])
IndexError: list index out of range
because when you run the script you need to supply a parameter, presumably the file name that you want to scan. If the file is called script.py you might run as:
python script.py name-of-file-to-scan
sys module provides access to any command-line arguments via the sys.argv.
Provide argument while running program.
ex:
python script.py file_name

python how to include a file of lists in a script

I have a file that gets generated by :
excerpt:
group0 = ['ParentPom']
group1 = ['Commons','http', 'availability','ingestPom','abcCommons','solrIndex','123Service']
...
group10=['totalCommons','Generator']
How can I include this in my python script, tried import but no luck
>>> import dependencies_custom
>>> print (group2[0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'group2' is not defined
In the import form you're using, you should be able to access the groups by
dependencies_custom.group2[0]
type notation. If you want just use just group2[0] notation, try using:
from dependencies_custom import *

Trouble Importing Pyshark

I'm using Pyshark and Python 2.6 on OS X 10.10. I simply try to import pyshark in my code, and this error is thrown. Any idea of what could be going wrong?
/System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 "/Users/spencergardner/Google Drive/development/python-sockets/sniff.py"
Traceback (most recent call last):
File "/Users/spencergardner/Google Drive/development/python-sockets/sniff.py", line 1, in <module>
import pyshark
File "/Library/Python/2.6/site-packages/pyshark/__init__.py", line 1, in <module>
from pyshark.capture.live_capture import LiveCapture
File "/Library/Python/2.6/site-packages/pyshark/capture/live_capture.py", line 1, in <module>
from pyshark.capture.capture import Capture
File "/Library/Python/2.6/site-packages/pyshark/capture/capture.py", line 12, in <module>
from pyshark.tshark.tshark_xml import packet_from_xml_packet, psml_structure_from_xml
File "/Library/Python/2.6/site-packages/pyshark/tshark/tshark_xml.py", line 5, in <module>
from pyshark.packet.layer import Layer
File "/Library/Python/2.6/site-packages/pyshark/packet/layer.py", line 57
return {slot: getattr(self, slot) for slot in self.__slots__}
^
SyntaxError: invalid syntax
The error is due to using a dictionary comprehension, a language feature that was introduced to Python 2 in 2.7, not the 2.6 you're trying to use. Apple ships OS X 10.10 with both 2.7 and 2.6. Is there a reason you can't use 2.7 instead?

Categories

Resources