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

时间:2019-06-17 18:14:36

标签: python linux ubuntu

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

0 * * * * /usr/bin/python3 /usr/folder/test.py

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

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

我尝试同时使用Path(filename).resolve()os.path.abspath(filename),但是它们都不起作用。

import os
print(os.path.abspath("checklist.txt"))
python3 usr/folder/test.py

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

  

python3 test.py

     

/usr/folder/checklist.txt

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

  

python3 usr / folder / test.py

     

/checklist.txt

2 个答案:

答案 0 :(得分: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')

答案 1 :(得分:2)

__ file__属性

import os
filename = 'checklist.txt'
abs_path_to_file = os.path.join(os.path.dirname(__file__), filename)

sys模块

import os, sys
filename = 'checklist.txt'
abs_path_to_file = os.path.join(os.path.dirname(sys.argv[0]), filename)