在脚本目录前添加一个字符串 [英] Prepend script's directory to a string

查看:55
本文介绍了在脚本目录前添加一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一次性脚本时,通常需要从与脚本相同的目录中加载配置文件,映像或诸如此类的东西.最好无论脚本从哪个目录执行,它都应继续正常工作,因此我们可能不希望仅依赖当前的工作目录.

When writing throwaway scripts it's often needed to load a configuration file, image, or some such thing from the same directory as the script. Preferably this should continue to work correctly regardless of the directory the script is executed from, so we may not want to simply rely on the current working directory.

如果在您从以下位置使用文件的同一文件中对其进行定义,则类似的方法就可以正常工作:

Something like this works fine if defined within the same file you're using it from:

from os.path import abspath, dirname, join

def prepend_script_directory(s):
    here = dirname(abspath(__file__))
    return join(here, s)

不希望将相同的函数复制粘贴或重写到每个模块中,但是存在一个问题:如果将其移动到单独的库中并作为函数导入,则__file__现在正在引用其他模块,并且结果不正确.

It's not desirable to copy-paste or rewrite this same function into every module, but there's a problem: if you move it into a separate library, and import as a function, __file__ is now referencing some other module and the results are incorrect.

我们也许可以改用它,但是sys.argv似乎也不可靠.

We could perhaps use this instead, but it seems like the sys.argv may not be reliable either.

def prepend_script_directory(s):
    here = dirname(abspath(sys.argv[0]))
    return join(here, s)

如何稳健正确地编写prepend_script_directory?

推荐答案

我每次执行脚本时,都会亲自将os.chdir放入脚本目录.只是:

I would personally just os.chdir into the script's directory whenever I execute it. It is just:

import os
os.chdir(os.path.split(__file__)[0])

但是,如果您确实想将此内容重构到库中,则实质上是需要一个知道其调用者状态的函数.因此,您必须做到

However if you did want to refactor this thing into a library, you are in essence wanting a function that is aware of its caller's state. You thus have to make it

prepend_script_directory(__file__, blah)

如果你只是想写

prepend_script_directory(blah)

您必须使用堆栈框架执行特定于cpython的技巧:

you'd have to do cpython-specific tricks with stack frames:

import inspect

def getCallerModule():
    # gets globals of module called from, and prints out __file__ global
    print(inspect.currentframe().f_back.f_globals['__file__'])

这篇关于在脚本目录前添加一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆