How can module determine its own path?
Robert Kern
robert.kern at gmail.com
Fri Oct 30 21:08:28 EDT 2009
Stef Mientki wrote:
> Robert Kern wrote:
>> On 2009-10-30 18:40 PM, Stef Mientki wrote:
>>> Robert Kern wrote:
>>>> On 2009-10-30 12:19 PM, kj wrote:
>>>>> How can a module determine the path of the file that defines it?
>>>>> (Note that this is, in the general case, different from sys.argv[0].)
>>>>
>>>> __file__
>>>>
>>> but for modules launched with execfile, __file__ doesn't exists.
>>
>> Modules launched from execfile() using a properly initialized
>> namespace dict do.
>>
> interesting,
> but how do I configure a "properly initialized namespace dict" (other
> than my current namespace) ?
filename = '...'
ns = dict(
__file__=filename,
__name__='whatever_you_need_it_to_be',
__builtins__=__builtins__,
)
execfile(filename, ns)
If you need to access variables in the current namespace:
filename = '...'
global_ns = globals().copy()
global_ns['__file__'] = filename
global_ns['__name__'] = 'whatever_you_need_it_to_be'
local_ns = locals().copy()
execfile(filename, global_ns, local_ns)
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list