简体   繁体   English

获取 docker 容器中 current.py 文件的绝对路径

[英]Get absolute path of current .py file in docker container

Im trying to get the absolute path of a.py file to access an other file which is located in the same directory ( /files ).我试图获取 a.py 文件的绝对路径以访问位于同一目录( /files )中的其他文件。 All files are mounted in a docker container as part of a jenkins pipeline.作为 jenkins 管道的一部分,所有文件都安装在 docker 容器中。 In the.py file I use the following syntax to get the absolute path:在 .py 文件中,我使用以下语法来获取绝对路径:

    from pathlib import Path

    current_dir = f"{Path(__file__).resolve().parent}/result.txt"

The file exists in the container but im receiving the following error:该文件存在于容器中,但我收到以下错误:

No such file or directory: '/tmp/.tmpAA7qY3/files/result.txt'

The Jenkins file looks like this: Jenkins 文件如下所示:

node('docker') {
    docker.image("circleci/python:3.7-buster").inside('--user root:root'+' -v /var/run/docker.sock:/var/run/docker.sock') {
        stage("Scan dependencies") {
            checkout scm
            sh 'poetry run pytest'
        }
    }
}

Jenkins will create a new temporary folder which is called workspace for each specific build instance. Jenkins将为每个特定的构建实例创建一个称为workspace的新临时文件夹。 Therefore your code is really in /tmp/.tmpAA7qY3 .因此,您的代码实际上位于/tmp/.tmpAA7qY3中。 Since you are running in the tmp folder, it's not strange that the __file__ will resolve to that path.由于您在 tmp 文件夹中运行,因此__file__将解析为该路径并不奇怪。

You need to find out where exactly the file you are searching will be located relative to your temporary folder, or as an absolute path.您需要找出您正在搜索的文件相对于您的临时文件夹的确切位置,或者作为绝对路径。 If you are not in control of how the file was created, easiest is to execute the find / -name result.txt and get the result.如果您无法控制文件的创建方式,最简单的方法是执行find / -name result.txt并获取结果。

If the file is created in another stage in the Jenkins pipeline flow, the file might not be in the container since each stage can create it's own container as explained here .如果该文件是在Jenkins管道流程的另一个阶段创建的,则该文件可能不在容器中,因为每个阶段都可以创建自己的容器,如此所述。

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

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