将脚本的目录添加到字符串前面
编写一次性脚本时,通常需要从与脚本相同的目录加载配置文件、图像或类似的东西。最好无论脚本从哪个目录执行,它都应该继续正常工作,因此我们可能不想简单地依赖当前工作目录。
如果在您使用它的同一个文件中定义,这样的东西可以正常工作:
from os.path import abspath, dirname, join
def prepend_script_directory(s):
here = dirname(abspath(__file__))
return join(here, s)
将相同的函数复制粘贴或重写到每个模块中是不可取的,但是存在一个问题:如果将其移动到单独的库中,然后导入作为一个函数,__file__
现在正在引用其他一些模块,并且结果不正确。
我们也许可以使用它,但似乎 sys.argv 也可能不可靠。
def prepend_script_directory(s):
here = dirname(abspath(sys.argv[0]))
return join(here, s)
如何稳健且正确地编写 prepend_script_directory
?
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)
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.
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)
How to write prepend_script_directory
robustly and correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
每当我执行脚本时,我个人都会将 os.chdir 放入脚本的目录中。只是:
但是,如果您确实想将这个东西重构到库中,那么您本质上需要一个能够了解其调用者状态的函数。因此,
如果你只是想写,
你必须使用堆栈帧执行特定于 cpython 的技巧:
I would personally just
os.chdir
into the script's directory whenever I execute it. It is just: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
If you just wanted to write
you'd have to do cpython-specific tricks with stack frames:
我认为它闻起来不正确的原因是
$PYTHONPATH
(或sys.path
)是正确使用的通用机制。I think the reason it doesn't smell right is that
$PYTHONPATH
(orsys.path
) is the proper general mechanism to use.你想要 pkg_resources
You want pkg_resources