简体   繁体   English

在Python中的Linux上的子目录中找到顶级目录

[英]Find top-level directory from subdirectory on Linux in Python

I am creating various HTML file parts, image thumbnails etc. from within a CodeIgniter application tree using cron-scheduled Python 2.7 programs on Linux. 我正在Linux上使用cron计划的Python 2.7程序从CodeIgniter应用程序树中创建各种HTML文件部分,图像缩略图等。 The actual Python programs exist under the CodeIgniter tree in a subdirectory one level below the application directory as follows. 实际的Python程序存在于CodeIgniter树下,位于应用程序目录下一层的子目录中,如下所示。

codeigniter/web-root 
    |
    application
    |   |    
    |   scripts
    |   |   |
    |   |   my-program.py
    |   | 
    |   database
    |       |
    |       database.sqlite 
    images

I want to determine the codeigniter/web-root directory from within my-program.py using methods from the os.path module. 我想使用os.path模块中的方法从my-program.py确定codeigniter/web-root目录。 However, the absolute path to the codeigniter/web-root is different on the development and production environments so I prefer not to hardwire this path information into the Python program itself. 但是,在开发和生产环境中,到达codeigniter/web-root的绝对路径有所不同,因此我不希望将此路径信息硬连接到Python程序本身。

The current script(s) use the following construct to determine the absolute path of "codeigniter/web-root" which is two directory levels above the script itself in both environments. 当前脚本使用以下结构来确定“ codeigniter / web-root”的绝对路径,这是两种环境中脚本本身的两个目录级别。

#!/bin/env python2.7

import os.path

ci_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

Is there a cleaner way to determine the top level(ci_root) directory without using multiple os.path.dirname calls? 有没有一种更清洁的方法来确定顶级(ci_root)目录,而无需使用多个os.path.dirname调用?

import os.path
print os.path.abspath(__file__+'/../../..')   # the directory three levels up

I was pleasantly surprised that 我很惊喜

  • abspath() managed to parse correctly, without using os.path.join() abspath()可以正确解析,而无需使用os.path.join()
  • We didn't have to strip out the filename before we build the path 在构建路径之前,我们不必去除文件名

For cross platform compatibility if abspath's parsing does not work, we could use something less readable, eg 为了实现跨平台兼容性,如果abspath的解析不起作用,我们可以使用可读性较低的内容,例如

  • os.path.sep instead of '/' os.path.sep而不是'/'
  • os.path.join() os.path.join()

Find the real path based on the relative path of "up three directories," and extract the last part of that real path. 根据“上三个目录”的相对路径找到真实路径,然后提取该真实路径的最后一部分。

[Edit: In response to your comment I have revised this. [编辑:针对您的评论,我对此进行了修改。 In my opinion it is getting complex enough that your chain of dirname 's is better. 在我看来,它变得越来越复杂,以至于您的dirname链更好。 At least it is easy to understand what it happening.] 至少很容易理解发生了什么。]

from os import path as p
_, ci_root = p.split(p.abspath(p.join(__file__, '../../..')))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM