Last active
September 12, 2021 00:30
-
-
Save himaprasoonpt/94c22b7138cd726ff3579d7a946ebac5 to your computer and use it in GitHub Desktop.
Block os import and any other system import in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from contextlib import contextmanager | |
@contextmanager | |
def block_system_import(): | |
block_import = ["os",'sys'] | |
saved = {} | |
import sys | |
for i in block_import: | |
saved[i] = sys.modules[i] | |
sys.modules[i] = None | |
yield None | |
for i in block_import: | |
sys.modules[i] = saved[i] | |
with block_system_import(): | |
try: | |
import sys | |
except ModuleNotFoundError: | |
print("Success could not import modules inside context manager") | |
import sys | |
import os | |
print("Import sys packages outside context manager succeeded") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment