why this works > varhelp = __import__("sys")
and this doesn't> varhelp = __import__("sys.path")
the second one throws:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named path

then how to achieve the second one?

Recommended Answers

Have you tried:

import sys.path

This actually ALSO throws an error because sys.path is not a module. path is just a variable inside the sys module. Here is an example that works:

foo = __import__("sys")
print foo.path

Does that make sense?

Jump to Post

The import statement will return the top level module of a package.
You can try this.

varhelp = __import__("sys").path

But be careful and try to keep "magic stuff" away from import statement.

Jump to Post

All 5 Replies

module = "sys"
method = "byteorder"

I also tried this way

        varHelp = __import__(module )
        varHelp2 =__import__(module+'.'+method )

but this is also giving error

Traceback (most recent call last):
  File "/Users/sanjeevkumar/Development/python/testing.py", line 113, in outputHelp
    varHelp2 =__import__(module+'.'+method )
ImportError: No module named byteorder

Have you tried:

import sys.path

This actually ALSO throws an error because sys.path is not a module. path is just a variable inside the sys module. Here is an example that works:

foo = __import__("sys")
print foo.path

Does that make sense?

not really, when i defined variables it I meant the module and method can be different.. in any case..

The import statement will return the top level module of a package.
You can try this.

varhelp = __import__("sys").path

But be careful and try to keep "magic stuff" away from import statement.
import(doc)

Note This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().

For the record, the way to achieve the results that I think the OP is looking for is to use

from sys import path

I prefer to import sys and use sys.path because it makes the namespaces obvious.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.