[英]How to get absolute path on linux when running from another location
I want to run a crontab which will run my file every hour at 0 minutes. 我想运行一个crontab,它将在0分钟每小时运行一次我的文件。 I have the (sudo) crontab set up with a single command as follows: 我使用单个命令设置(sudo)crontab,如下所示:
0 * * * * /usr/bin/python3 /usr/folder/test.py
The crontab is running and as far as I can tell is correct, but my python file is not returning the absolute path when the file is run from another location. crontab正在运行,据我所知是正确的,但是当从另一个位置运行文件时,我的python文件没有返回绝对路径。
What I need is a way to guarantee the absolute path of this text file when it is accessed from the root so that my crontab can run the file. 我需要的是一种方法来保证从root访问它时文本文件的绝对路径,以便我的crontab可以运行该文件。
I've tried using both Path(filename).resolve()
, and os.path.abspath(filename)
but neither of them work. 我尝试过使用Path(filename).resolve()
和os.path.abspath(filename)
但它们都不起作用。
import os
print(os.path.abspath("checklist.txt"))
python3 usr/folder/test.py
When I run the file "test.py" while within the folder, I get the expected output 当我在文件夹中运行文件“test.py”时,我得到了预期的输出
python3 test.py python3 test.py
/usr/folder/checklist.txt /usr/folder/checklist.txt
however when I run the same file from the root and access it via a path I get a different result, making using crontab impossible in this context 然而,当我从根运行相同的文件并通过路径访问它时,我得到了不同的结果,在这种情况下使用crontab是不可能的
python3 usr/folder/test.py python3 usr / folder / test.py
/checklist.txt /checklist.txt
If checklist.txt
is in the same folder as your test.py
script, then you can use the __file__
variable to get the right path. 如果checklist.txt
与test.py
脚本位于同一文件夹中,则可以使用__file__
变量来获取正确的路径。 For example 例如
# 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')
__file__ attribute __file__属性
import os
filename = 'checklist.txt'
abs_path_to_file = os.path.join(os.path.dirname(__file__), filename)
sys module sys模块
import os, sys
filename = 'checklist.txt'
abs_path_to_file = os.path.join(os.path.dirname(sys.argv[0]), filename)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.