【问题标题】:How to get absolute path on linux when running from another location从另一个位置运行时如何在linux上获取绝对路径
【发布时间】:2019-06-17 18:14:36
【问题描述】:

我想运行一个 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

【问题讨论】:

标签: python linux ubuntu


【解决方案1】:

如果checklist.txt 与您的test.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')

【讨论】:

  • 非常感谢!几个小时以来一直在拉我的头发。
【解决方案2】:

__file__ 属性

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

系统模块

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

【讨论】:

    猜你喜欢
    • 2011-03-21
    • 1970-01-01
    • 2010-09-21
    • 2016-04-22
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    相关资源
    最近更新 更多