Self-awareness of imported modules? Do they know where they live?

M

Martin M.

Hi,

I have the following question: How can an imported module see/find the
path to itself?

Background: From my main script I import a module which needs a file
(AppleScript) located in the same directory as the imported module.
What I do not want is to tell the module the location of the
AppleScript file by passing this information from the main script,
because I want my imported module to be independent from the main
script.

So how can I do this? In AppleScript I would try something like "path
to me", but this does not work for imported scripts in AppleScript, as
you then only get the path to the main script. But can this be done in
Python? Can modules know where they are currently located, where they
live? Can they be self-aware?

I hope you understand my problem and I appreciate any helpful answers!

Happy scripting!

Martin

P.S.: Background-background: I try to build myself a library of Python
scripts, which are getting a lot of infro from AppleScripts which
reside in the same directoty (e.g. usrdrs.py & usrdrs.scpt, usrdrs.py
is reading/executing usrdrs.scpt and returning the gathered info).
 
H

Heiko Wundram

Martin said:
So how can I do this? In AppleScript I would try something like "path
to me", but this does not work for imported scripts in AppleScript, as
you then only get the path to the main script. But can this be done in
Python? Can modules know where they are currently located, where they
live? Can they be self-aware?

Yes, they can be:

modelnine@phoenix ~ $ cat test.py
import os

print os.path.abspath(__file__)
modelnine@phoenix ~ $ python test.py
/home/modelnine/test.py
modelnine@phoenix ~ $

HTH!

--- Heiko.
 
M

Martin M.

Hi Heiko,

Thanks so much for your help! I just tested it and it works like a
charm!

****Test File 1****
-- main.py
#!/usr/bin python

from lib import being

being.location()

****Test File 2****
-- being.py
#!/usr/bin/python

import os

def location():
print os.path.abspath(__file__)
****
results in:
martin% python main.py
/Volumes/CodeIsland/Projects/glashaus/glashaus0.1a/lib/being.pyc

Now I can use os.path.split() to get the parent directory and
os.path.join() to target my AppleScript file.

Thanks again!

Martin M.
 
S

Simon Brunning

The only self aware Python scripts that I'm aware are the timbot and
the effbot. Their sources are available from the PSU website at
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top