I want to establish a standard script file that is imported into python at startup using the PYTHONSTARTUP environment variable. Additionally, I want to be able to conveniently reload the same script file after modifying it in an external editor, to test its behavior after the modification. I created a ~/.pythonrc.py file and set it as PYTHONSTARTUP:
import os
import imp
def load_wb():
_cwd = os.getcwd()
os.chdir(os.path.join(os.getenv('HOME'),'S开发者_运维问答kripte'))
import workbench
imp.reload(workbench)
os.chdir(_cwd)
load_wb()
This is my very minimal script file for the start:
def dull_function():
print('Not doing much...')
print('Workbench loaded.')
When I launch Python 3.1.2, .pythonrc is successfully executed and the workbench.py is imported, but dull_function does not appear in the global namespace or in a local one. What do I have to do differently?
Move the import
statement outside the function. You're basically importing the workbench
module into the function scope, not the global scope (Try calling workbench.dull_function
from inside load_wb
to see for yourself).
In other words, change your code to:
import os
import imp
import workbench
def load_wb():
_cwd = os.getcwd()
os.chdir(os.path.join(os.getenv('HOME'), 'Skripte'))
imp.reload(workbench)
os.chdir(_cwd)
load_wb()
Not really solving your immediate problem but... You might appreciate using iPython shell for testing in that case. Using the autoimport functionality, you can mark a module for (re)loading on each executed line if needed.
That means you can %aimport workbench
and then every time you run some_function_Im_testing()
, workbench
will be reloaded if it changed. Just add the autoimport line into the configuration file for ipython and you're done.
精彩评论