从另一个位置运行时如何在Linux上获取绝对路径

Con*_*nch 2 python linux ubuntu

我想运行一个crontab,它将在0分钟每小时运行一次我的文件。我使用单个命令设置了(sudo)crontab,如下所示:

0 * * * * /usr/bin/python3 /usr/folder/test.py
Run Code Online (Sandbox Code Playgroud)

crontab正在运行,据我所知是正确的,但是当从另一个位置运行该文件时,我的python文件未返回绝对路径。

我需要的是一种确保从根目录访问此文本文件时的绝对路径的方法,以便我的crontab可以运行该文件。

我已经尝试使用两者Path(filename).resolve()os.path.abspath(filename)但是它们都不起作用。

0 * * * * /usr/bin/python3 /usr/folder/test.py
Run Code Online (Sandbox Code Playgroud)
import os
print(os.path.abspath("checklist.txt"))
Run Code Online (Sandbox Code Playgroud)

当我在文件夹中运行文件“ test.py”时,得到了预期的输出

python3 test.py

/usr/folder/checklist.txt

但是,当我从根目录运行同一文件并通过路径访问它时,会得到不同的结果,因此在这种情况下无法使用crontab

python3 usr / folder / test.py

/checklist.txt

Jac*_*ack 6

如果checklist.txttest.py脚本位于同一文件夹中,则可以使用该__file__变量获取正确的路径。例如

# The directory that 'test.py' is stored
directory = os.path.dirname(os.path.abspath(__file__))
# The path to the 'checklist.txt'
checklist_path = os.path.join(directory, 'checklist.txt')
Run Code Online (Sandbox Code Playgroud)