For fun/to practice python, I am trying to create a program that displays the contents of a module. Looks like this:
import sys
print "Here are all the functions in the sys module: "
print dir(sys)
function = raw_input("Pick a function to see: ")
cnt = True
while cnt:
if function in dir(sys):
print "You chose:", function
cnt = False
else:
print "Invalid choice, please select again."
cnt = True
print dir("sys." + function)
But every time, no matter what string the variable function
is set to, the dir("sys." + function)
call always defaults to the same output as dir(string)
(or so I think!)
What is happening and is there a way for me to do this properly and get the output I really want (for example, the variable function
is set to stdin
and I get the output for dir(sys.stdin)
)?
You want to retrieve the actual object from the module; use the getattr()
function for that:
print dir(getattr(sys, function))
dir()
does not interpret the contents of the objects you pass to it; a string that happens to contain a value that corresponds to the name of a function in a module is not dereferenced for you.