/path1 # "import bar" causes the line "print(os.getcwd())" to run/path2/bar.py # then "print(__file__)" runs/path2/bar.py # then the import statement finishes and "print(bar.__file__)" runs
但是,如果您尝试自己运行bar.py,您将获得:
/path2 # "print(os.getcwd())" still works fineTraceback (most recent call last): # but __file__ doesn't exist if bar.py is running as mainFile "/path2/bar.py", line 3, in <module>print(__file__)NameError: name '__file__' is not defined
import os,sysif hasattr(sys,'frozen'): # only when running in py2exe this existsbase = sys.prefixelse: # otherwise this is a regular python scriptbase = os.path.dirname(os.path.realpath(__file__))
global modpathmodname = 'os' #This can be any module name on the fly#Create a file called "modname.py"f=open("modname.py","w")f.write("import "+modname+"\n")f.write("modpath = "+modname+"\n")f.close()#Call the file with execfile()execfile('modname.py')print modpath<module 'os' from 'C:\Python27\lib\os.pyc'>