问题
I want to know how to make variables from functions in imported modules available in the IPython interactive namespace.
I have some example code which I want to run from another script so I set it up as run_test.py:
def run_test():
a = 5
if __name__ == "__main__":
run_test()
I import the module as follows and call the function:
import run_test
run_test.run_test()
How do I make variable 'a' available in the interactive namespace? The only way I can do it is to make 'a' a global and run run_test.py directly rather than importing it and calling the function.
Any pointers appreciated.
回答1:
I believe this can be accomplished by returning locals and then updating locals.
def main():
# do things
return locals()
if __name__ == '__main__':
new_locals = main()
locals().update(new_locals)
This seems to work, though it feels like a hack, so perhaps it won't always.
A reasonable example of where you want this: If you want access to all the variables in a function's namespace, but don't want that function's variables accessible to other parts of a script (i.e., other function definitions).
来源:https://stackoverflow.com/questions/28432412/making-function-variables-from-imported-module-available-in-ipython-interactive