微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决我如何在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__);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。