You are on page 1of 2

import pickle

import builtins
import io
import json

# Enter your code here.


import pickle
import os
data={
"a":[5,9],
"b":[5,6],
"c":["Pickle is","helpful"]
}
#Dump file in pickle
with open("test.pkl","wb") as outfile:
pickle.dump(data,outfile)

del data
#Read data back from pickle
with open("test.pkl","rb") as outfile:
data=pickle.load(outfile)

print(data)
pickles = []
for root,dirs,files in os.walk("./"):
# root is the dir we are currently in, f the filename that ends on ...
pickles.extend( (os.path.join(root,f) for f in files if
f.endswith(".pkl")) )
pickles=str(pickles)
print(pickles)

with open('.hidden.txt','w') as outfile:


outfile.write(pickles)

#2
class Player:
def __init__(self, name,runs):
self.name=name
self.runs=runs

myPlayer=Player('dhoni','10000')
pickle.dump(myPlayer,file=open('test.pickle','wb'),protocol=pickle.HIGHEST_PROTO
COL)
del myPlayer
myPlayer=pickle.load(file=open('test.pickle','rb'))
print(myPlayer.name)
print(myPlayer.runs)

#3
import os
import builtins
import pickle
import sys
sys.tracebacklimit=0
import traceback
import io
from logging import Logger

safe_builtins = {
'range',
'complex',
'set',
'frozenset'#,
#'slice',
}

class RestrictedUnpickler(pickle.Unpickler):

def find_class(self, module, name):


# Only allow safe classes from builtins.
if module == "builtins" and name in safe_builtins:
return getattr(builtins, name)
# Forbid everything else.
raise pickle.UnpicklingError("global '%s.%s' is forbidden" %(module,
name))

def restricted_loads(s):
"""Helper function analogous to pickle.loads()."""
return RestrictedUnpickler(io.BytesIO(s)).load()

#restricted_loads(pickle.dumps([5,3,range(20)]))

def func1(a):
try:

#x=restricted_loads(a)
#return x
return a
except pickle.UnpicklingError :
s=traceback.format_exc()

return s

def func2(s):
try:
a=slice(0,8,3)
x=restricted_loads(pickle.dumps(a))
return s[x]
#return s
except pickle.UnpicklingError :
s=traceback.format_exc()
return s

if __name__ == "__main__":
a=range(int(input()))
b=func1(a)
print(b)
y=tuple(input())
z=func2(y)
print(z)

You might also like