Skip to content

Instantly share code, notes, and snippets.

@himaprasoonpt
Last active September 12, 2021 00:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save himaprasoonpt/94c22b7138cd726ff3579d7a946ebac5 to your computer and use it in GitHub Desktop.
Save himaprasoonpt/94c22b7138cd726ff3579d7a946ebac5 to your computer and use it in GitHub Desktop.
Block os import and any other system import in python
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