I want to get the file path of the current file in Digital Micrograph in python
. How do I do this?
I tried to use
__file__
but I get NameError: Name not found globally.
I tried to use the dm-script
GetCurrentScriptSourceFilePath()
with the following code to get the value to python
import DigitalMicrograph as DM
import time
# get the __file__ by executing dm-scripts GetCurrentScriptSourceFilePath()
# function, then save the value in the persistent tags and delete the key
# again
tag = "__python__file__{}".format(round(time.time() * 100))
DM.ExecuteScriptString(
"String __file__;\n" +
"GetCurrentScriptSourceFilePath(__file__);\n" +
"number i = GetPersistentTagGroup().TagGroupCreateNewLabeledTag(\"" + tag + "\");\n" +
"GetPersistentTagGroup().TagGroupSetIndexedTagAsString(i, __file__);\n"
);
_, __file__ = DM.GetPersistentTagGroup().GetTagAsString(tag);
DM.ExecuteScriptString("GetPersistentTagGroup().TagGroupDeleteTagWithLabel(\"" + tag + "\");")
but it seems that the GetCurrentScriptSourceFilePath()
function does not contain a path (which makes sense because it is executed from a string).
I found this post recommending
import inspect
src_file_path = inspect.getfile(lambda: None)
but the src_file_path
is "<string>"
which is obviously wrong.
I tried to raise an exception and then get the filename of it with the following code
try:
raise Exception("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
filename = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print("File: ", filename)
but again I get <string>
as the filename
.
I tried to get the path out of the script window but I could not find any function to get it. But the script window has to know where its path is, otherwise Ctrl+S cannot work.
Some background
I am developing a module used for Digital Micrograph. There I also have test files. But to import the (still developed) module in the test file(s), I need the path relative to the test file.
Later the module will be installed somewhere so this should not be a problem then. But for offering a compelte set of tests, I want to be able to execute the tests without having to install the (not working) module.