从Python中的不同工作目录确定文件的路径名
我有一个在我的几个项目之间共享的 python 模块(每个项目都有不同的工作目录)。该共享模块中的函数之一使用 os.spawn 执行脚本。问题是,我不确定要为 os.spawn 指定什么路径名,因为我不知道调用该函数时当前工作目录是什么。如何以任何调用者都可以找到的方式引用该文件?谢谢!
I have a python module that is shared among several of my projects (the projects each have a different working directory). One of the functions in this shared module, executes a script using os.spawn. The problem is, I'm not sure what pathname to give to os.spawn since I don't know what the current working directory will be when the function is called. How can I reference the file in a way that any caller can find it? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
所以我刚刚了解了 __file__ 变量,它将为我的问题提供解决方案。我可以使用 file 获取在所有项目中保持不变的路径名,并使用它来引用我需要调用的脚本,因为该脚本将始终位于相对于
的相同位置__文件__ 。但是,如果有人有其他/更好的方法,我愿意接受。
So I just learned about the
__file__
variable, which will provide a solution to my problem. I can use file to get a pathname which will be constant among all projects, and use that to reference the script I need to call, since the script will always be in the same location relative to__file__
. However, I'm open to other/better methods if anyone has them.将其放在众所周知的目录中(/usr/lib/yourproject/ 或 ~/lib 或类似目录),或者根据使用它的源文件的位置将其放在众所周知的相对路径中。
Put it in a well known directory (/usr/lib/yourproject/ or ~/lib or something similar), or have it in a well known relative path based on the location of your source files that are using it.
下面的代码将找到调用模块的位置,这从程序员的角度来看是有意义的:
即,如果您的项目位于 /home/foo/project 中,并且您想要引用script / myscript 中的 script 'myscript' ,您可以简单地传递 'scripts/myscript' 。该代码片段将确定调用者位于 /home/foo/project 中,并且整个路径应为 /home/foo/projects/scripts/myscript。
或者,您始终可以要求程序员指定完整路径,并使用 os.path.exists 检查它是否存在。
The following piece of code will find the location of the calling module, which makes sense from a programmer's point of view:
I.e. if your project lives in /home/foo/project, and you want to reference a script 'myscript' in scripts/, you can simply pass 'scripts/myscript'. The snippet will figure out the caller is in /home/foo/project and the entire path should be /home/foo/projects/scripts/myscript.
Alternatively, you can always require the programmer to specify a full path, and check using os.path.exists if it exists.
您可能会在 PyCon 2010 演示文稿中找到有关跨平台应用程序开发和分发的材料有用。他们解决的问题之一是跨平台一致地查找数据文件,并用于代码的安装与开发检查。
You might find the materials in this PyCon 2010 presentation on cross platform application development and distribution useful. One of the problems they solve is finding data files consistently across platforms and for installed vs development checkouts of the code.