access module 'sys' without using import machinery

  • Last Update :
  • Techknowledgy :

For Python 3 this comment from eryksun works, for example:

>>> f = [t for t in ().__class__.__base__.__subclasses__()
... if t.__name__ == 'Sized'][0].__len__
>>> f.__globals__['__builtins__']['__import__']('sys')
<module 'sys' (built-in)>

In Python 2, you just look for a different object:

>>> f = [t for t in ().__class__.__base__.__subclasses__()
... if t.__name__ == 'catch_warnings'][0].__exit__.__func__
>>> f.__globals__['__builtins__']['__import__']('sys')
<module 'sys' (built-in)>

However, many of those __globals__ objects are bound to have sys present already. Searching for a sys module on Python 3, for example, gives me access to one in a flash:

>>> next(getattr(c, f).__globals__['sys']
... for c in ().__class__.__base__.__subclasses__()
... for f in dir(c)
... if isinstance(getattr(c, f, None), type(lambda: None)) and
... 'sys' in getattr(c, f).__globals__)
<module 'sys' (built-in)>

Suggestion : 2

The import machinery is extensible, so new finders can be added to extend the range and scope of module searching.,The following sections describe the protocol for finders and loaders in more detail, including how you can create and register new ones to extend the import machinery.,Finders do not actually load modules. If they can find the named module, they return a module spec, an encapsulation of the module’s import-related information, which the import machinery then uses when loading the module.,The import machinery fills in these attributes on each module object during loading, based on the module’s spec, before the loader executes the module.

parent /
   __init__.py
one /
   __init__.py
two /
   __init__.py
three /
   __init__.py
module = None
if spec.loader is not None and hasattr(spec.loader, 'create_module'):
   # It is assumed 'exec_module'
will also be defined on the loader.
module = spec.loader.create_module(spec)
if module is None:
   module = ModuleType(spec.name)
# The
import -related module attributes get set here:
   _init_module_attrs(spec, module)

if spec.loader is None:
   # unsupported
raise ImportError
if spec.origin is None and spec.submodule_search_locations is not None:
   # namespace package
sys.modules[spec.name] = module
elif not hasattr(spec.loader, 'exec_module'):
   module = spec.loader.load_module(spec.name)
# Set __loader__ and __package__
if missing.
else:
   sys.modules[spec.name] = module
try:
spec.loader.exec_module(module)
except BaseException:
   try:
   del sys.modules[spec.name]
except KeyError:
   pass
raise
return sys.modules[spec.name]
spam /
   __init__.py
foo.py
from.foo
import Foo
>>> import spam
>>> spam.foo
<module 'spam.foo' from '/tmp/imports/spam/foo.py'>
   >>> spam.Foo
   <class 'spam.foo.Foo'>
package /
   __init__.py
subpackage1 /
   __init__.py
moduleX.py
moduleY.py
subpackage2 /
   __init__.py
moduleZ.py
moduleA.py

Suggestion : 3

September 10, 2018May 18, 2021

If you know some of the imported manners in another programming language, you will find in the code calls to functions of this kind < module_name >.< function >, Some of the import standard modules are in python is :

import getopt
import os
import re
import string
import sys
import getpass
import urllib
import subprocess

For example, the module sys allows you to do this:

import sys
#down
if something
sys.exit(0)

This is an example of factorial in python, using a factorial function of standard math module.

import math
print(math.factorial(5))

See this example not suing the math module, because all important to direct use.

from math
import *

print(fsum([1, 2, 3, 1]))
print(factorial(5))

Suggestion : 4

Last Updated : 26 Jul, 2022

Output:

The value of pi is: ', 3.141592653589793

3.14159265359
720

3.14159265359
720

Suggestion : 5

If the requested module already exists in sys.modules, that module should be used and reloaded. Otherwise the loader should create a new module and insert it into sys.modules before any loading begins, to prevent recursion from the import. If the loader inserted a module and the load fails, it must be removed by the loader from sys.modules; modules already in sys.modules before the loader began execution should be left alone (see importlib.util.module_for_loader()).,If an exception is raised by the decorated method and a module was added to sys.modules, then the module will be removed to prevent a partially initialized module from being in left in sys.modules. If the module was already in sys.modules then it is left alone.,A legacy method for loading a module. If the module cannot be loaded, ImportError is raised, otherwise the loaded module is returned.,Find the loader for a module, optionally within the specified path. If the module is in sys.modules, then sys.modules[name].__loader__ is returned (unless the loader would be None or is not set, in which case ValueError is raised). Otherwise a search using sys.meta_path is done. None is returned if no loader is found.

try:
cache
except NameError:
   cache = {}
object
   +
   --Finder(deprecated) |
   + --MetaPathFinder |
   + --PathEntryFinder +
   --Loader +
   --ResourceLoader-- -- -- -- +
   + --InspectLoader |
   + --ExecutionLoader-- +
   + --FileLoader +
   --SourceLoader
suffixes = importlib.machinery.SOURCE_SUFFIXES
loader = importlib.machinery.SourceFileLoader
lazy_loader = importlib.util.LazyLoader.factory(loader)
finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes))
import importlib

itertools = importlib.import_module('itertools')
import importlib.util
import sys

# For illustrative purposes.
name = 'itertools'

spec = importlib.util.find_spec(name)
if spec is None:
   print("can't find the itertools module")
else:
   # If you chose to perform the actual
import...
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Adding the module to sys.modules is optional.
sys.modules[name] = module
import importlib.util
import sys

# For illustrative purposes.
import tokenize
file_path = tokenize.__file__
module_name = tokenize.__name__

spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Optional;
only necessary
if you want to be able to
import the module
# by name later.
sys.modules[module_name] = module

Suggestion : 6

An abstract method that executes the module in its own namespace when a module is imported or reloaded. The module should already be initialized when exec_module() is called.,If the requested module already exists in sys.modules, that module should be used and reloaded. Otherwise the loader should create a new module and insert it into sys.modules before any loading begins, to prevent recursion from the import. If the loader inserted a module and the load fails, it must be removed by the loader from sys.modules; modules already in sys.modules before the loader began execution should be left alone (see importlib.util.module_for_loader()).,A legacy method for loading a module. If the module cannot be loaded, ImportError is raised, otherwise the loaded module is returned.,Find the loader for a module, optionally within the specified path. If the module is in sys.modules, then sys.modules[name].__loader__ is returned (unless the loader would be None or is not set, in which case ValueError is raised). Otherwise a search using sys.meta_path is done. None is returned if no loader is found.

try:
cache
except NameError:
   cache = {}
object
   +
   --Finder(deprecated) |
   + --MetaPathFinder |
   + --PathEntryFinder +
   --Loader +
   --ResourceLoader-- -- -- -- +
   + --InspectLoader |
   + --ExecutionLoader-- +
   + --FileLoader +
   --SourceLoader