Script to print names in Python modules
<p>The following script isn't printing names contained within each Python module in the list. When I run it, each dir(mod) command returns the same list of names. It's like the 'mod' variable isn't being understood by dir. The for loop doesn't appear to be the problem. Any ideas how to fix?</p>

<pre><code>#!/usr/bin/python

# Print out names in modules
# https://docs.python.org/2/py-modindex.html
import os, sys, re, subprocess, platform, shutil, argparse, test, xml, time, urllib2, getopt

def print_modules(module_list):
    for mod in module_list:
        print '------------'
        print mod
        print '------------'
        print dir(mod)
        print

# Use split() on a string to create a list (the lazy way!)
module_list = 'os sys list __builtins__ re subprocess platform shutil argparse test xml time urllib2 getopt'.split()
print type(module_list)
print_modules (module_list)
</code></pre>

<p>Problem is you are passing module name as variable to <code>dir</code> function.
Since module name is passed in variable, it is considering as string and <code>dir</code> is giving output for string.</p>

<pre><code>&gt;&gt;&gt;
&gt;&gt;&gt;
&gt;&gt;&gt; mod = 'os'
&gt;&gt;&gt;
&gt;&gt;&gt; dir(mod)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__
format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__get
slice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mo
d__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
 '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook
__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center',
 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index
', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', '
rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', '
strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
&gt;&gt;&gt;
&gt;&gt;&gt; type(mod)
&lt;type 'str'&gt;
&gt;&gt;&gt;
&gt;&gt;&gt;
&gt;&gt;&gt; import os
&gt;&gt;&gt;
&gt;&gt;&gt; type(os)
&lt;type 'module'&gt;
&gt;&gt;&gt;
&gt;&gt;&gt; dir(os)
['F_OK', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM',
 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT',
 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAI
T', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'UserDict', 'W_OK', '
X_OK', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', '__name__',
 '__package__', '_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list'
, '_make_stat_result', '_make_statvfs_result', '_pickle_stat_result', '_pickle_s
tatvfs_result', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closera
nge', 'curdir', 'defpath', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error'
, 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe'
, 'extsep', 'fdopen', 'fstat', 'fsync', 'getcwd', 'getcwdu', 'getenv', 'getpid',
 'isatty', 'kill', 'linesep', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir',
'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'popen2', 'popen3'
, 'popen4', 'putenv', 'read', 'remove', 'removedirs', 'rename', 'renames', 'rmdi
r', 'sep', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'startfile', 'stat', 'stat_
float_times', 'stat_result', 'statvfs_result', 'strerror', 'sys', 'system', 'tem
pnam', 'times', 'tmpfile', 'tmpnam', 'umask', 'unlink', 'unsetenv', 'urandom', '
utime', 'waitpid', 'walk', 'write']
&gt;&gt;&gt;
</code></pre>

<p>After getting module name as variable, we need to evaluate as module.
So, we will require <code>importlib</code> module which convert it into module.</p>

<p><strong>Code :</strong></p>

<pre><code>#!/usr/bin/python

# Print out names in modules
# https://docs.python.org/2/py-modindex.html
import os, sys, re, subprocess, platform, shutil, argparse, test, xml, time, urllib2, getopt
import importlib

def print_modules(module_list):


    for mod in module_list:
        module = importlib.import_module(mod, package=None)
        print '------------'
        print mod
        print '------------'
        print dir(module)
        print

# Use split() on a string to create a list (the lazy way!)
module_list = 'os sys'.split()
print type(module_list)
print_modules (module_list)
</code></pre>

<p><strong>Output:</strong></p>

<pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python c.py
&lt;type 'list'&gt;
------------
os
------------
['F_OK', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM',
 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT',
 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAI
T', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'UserDict', 'W_OK', '
X_OK', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', '__name__',
 '__package__', '_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list'
, '_make_stat_result', '_make_statvfs_result', '_pickle_stat_result', '_pickle_s
tatvfs_result', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closera
nge', 'curdir', 'defpath', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error'
, 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe'
, 'extsep', 'fdopen', 'fstat', 'fsync', 'getcwd', 'getcwdu', 'getenv', 'getpid',
 'isatty', 'kill', 'linesep', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir',
'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'popen2', 'popen3'
, 'popen4', 'putenv', 'read', 'remove', 'removedirs', 'rename', 'renames', 'rmdi
r', 'sep', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'startfile', 'stat', 'stat_
float_times', 'stat_result', 'statvfs_result', 'strerror', 'sys', 'system', 'tem
pnam', 'times', 'tmpfile', 'tmpnam', 'umask', 'unlink', 'unsetenv', 'urandom', '
utime', 'waitpid', 'walk', 'write']

------------
sys
------------
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__s
tderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_g
etframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorde
r', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_
write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix
', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckint
erval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursi
onlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversi
on', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'pa
th', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'py3kwarning', '
setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'std
in', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']



C:\Users\dinesh_pundkar\Desktop&gt;
</code></pre>

python module directory names