【发布时间】:2020-08-20 07:37:17
【问题描述】:
我想在python 中获取Digital Micrograph 中当前文件的文件路径。我该怎么做?
我尝试使用
__file__
但我得到NameError: Name not found globally.
我尝试使用 dm-script GetCurrentScriptSourceFilePath() 和以下代码来获取 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 + "\");")
但似乎GetCurrentScriptSourceFilePath() 函数不包含路径(这是有道理的,因为它是从字符串执行的)。
我发现this post推荐
import inspect
src_file_path = inspect.getfile(lambda: None)
但src_file_path 是"<string>",这显然是错误的。
我尝试引发异常,然后使用以下代码获取它的文件名
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)
但我再次将<string> 视为filename。
我试图从脚本窗口中获取路径,但找不到任何函数来获取它。但是脚本窗口必须知道它的路径在哪里,否则Ctrl+S不能工作。
一些背景
我正在开发一个用于数码显微照片的模块。那里我也有测试文件。但是要在测试文件中导入(仍在开发的)模块,我需要相对于测试文件的路径。
稍后模块将安装在某个地方,所以这应该不是问题。但是为了提供一组完整的测试,我希望能够执行测试而无需安装(不工作的)模块。
【问题讨论】: