我如何在python dm-script中获取当前文件路径

问题描述

我想在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 无效。


某些背景

我正在开发用于数字显微照片的模块。那里我也有测试文件。但是要将(仍在开发中的)模块导入测试文件中,我需要相对于测试文件的路径。

稍后,该模块将安装在某处,因此这应该不是问题。但是,为了提供一组完整的测试,我希望能够执行测试而不必安装(不工作)模块。

解决方法

对于当前工作目录的文件路径,请使用:

import os
os.getcwd()
,

在DM脚本(可以从Python脚本调用)中,命令GetApplicationDirectory()为您提供所需的内容。通常,您可能希望使用“ open_save”之一,即

GetApplicationDirectory("open_save",0)

这将返回使用File / Open或在新图像上使用File / Save时出现的目录(字符串变量)。但是,它不是“文件/保存工作区”或其他保存上使用的内容。

有关该命令的F1帮助文档中的内容: enter image description here

请注意,在Win10上,包括GMS在内的应用程序在“当前”目录的概念上有些破绽。特别是“ SetApplicationDirectory”命令并非总是能按预期运行...


如果要找出当前显示的特定文档的文件夹(图像或文本),可以使用以下DM脚本。这里的假设是,该窗口是最前面的窗口。

documentwindow win = GetDocumentWindow(0)
if ( win.WindowIsvalid() )
    if ( win.WindowIsLinkedToFile() )
        Result("\n" + win.WindowGetCurrentFile())
    
,

对于也需要此代码(并且只想复制一些代码)的每个人,我基于@BmyGuests答案创建了以下代码。这将获取脚本窗口绑定到的文件,并将其另存为持久性标记。然后从python文件中读取此标签(并删除该标签)。

重要说明:仅在python脚本窗口中,您可以按 Execute Script 按钮,并且仅在保存此文件后才能使用!但是从那里开始,您可能正在导入应该提供module.__file__属性的脚本。此操作不适用于插件/库

import DigitalMicrograph as DM

# the name of the tag is used,this is deleted so it shouldn't matter anyway
file_tag_name = "__python__file__"
# the dm-script to execute,double curly brackets are used because of the 
# python format function
script = ("\n".join((
    "DocumentWindow win = GetDocumentWindow(0);","if(win.WindowIsvalid()){{","if(win.WindowIsLinkedToFile()){{","TagGroup tg = GetPersistentTagGroup();","if(!tg.TagGroupDoesTagExist(\"{tag_name}\")){{","number index = tg.TagGroupCreateNewLabeledTag(\"{tag_name}\");","tg.TagGroupSetIndexedTagAsString(index,win.WindowGetCurrentFile());","}}","else{{","tg.TagGroupSetTagAsString(\"{tag_name}\","}}"
))).format(tag_name=file_tag_name)

# execute the dm script
DM.ExecuteScriptString(script)

# read from the global tags to get the value to the python script
global_tags = DM.GetPersistentTagGroup()
if global_tags.IsValid():
    s,__file__ = global_tags.GetTagAsString(file_tag_name);
    if s:
        # delete the created tag again
        DM.ExecuteScriptString(
            "GetPersistentTagGroup()." + 
            "TagGroupDeleteTagWithLabel(\"{}\");".format(file_tag_name)
        )
    else:
        del __file__

try:
    __file__
except NameError:
    # set a default if the __file__ could not be received
    __file__ = ""
    
print(__file__);

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...