0

I have written a small Windows Service compiled to an exe using py2exe, which from I read a file. It works great - however - I can only use an absolute path to access the file, using a relative path won't work. In .net you can do something like:

System.Reflection.Assembly.GetEntryAssembly().Location

To get the path to the .exe file, is there an option similar to this but for Python?

Best Regards,

Anders

1 Answer 1

1

You have a couple of options. If you already have a module object, you can do <module>.__file__ to get the path:

>>> import time
>>> time.__file__
'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/time.so'

However, often times you want to know the location of your current module, in which case you can use:

import inspect

path = inspect.currentframe().f_code.co_filename

(Also keep in mind that this can be anything that can be loaded by Python - so it can be a .pyd, .pyc, .so, .dll, etc.)

Sign up to request clarification or add additional context in comments.

2 Comments

@martineau: They both work, it's just a question of what you have as input. If you're in the module whose code you want to locate, you have to use the second one.
I looked at a standard module in python, for example, json used the first example, then did a split on .exe since that is included in the path. And everything before that is the relative path.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.