【问题标题】:How to set os.path correctly. Shows a different path when ran by systemd service如何正确设置 os.path。由 systemd 服务运行时显示不同的路径
【发布时间】:2023-01-24 13:49:33
【问题描述】:

我有一个 python 代码,其中包含名为 pythontut.db 的数据库文件(.py 和 db 文件位于同一文件夹中)。我使用 OS.path 进行路径设置。当它在 thonny 中执行时它工作正常,我创建了一个 systemd 服务以在重新启动时运行。但在重新启动时,路径不同并抛出“无法打开数据库”错误。

我试过像这样在pi-main.py中设置路径

dbname = 'pythontut.db'
scriptdir = os.getcwd()
db_path = os.path.join(scriptdir, dbname)
print(db_path)

它像这样在 thonny 中显示输出(Python 文件和数据库在同一个文件夹中)

/home/pi/pi-project/pythontut.db

但是当它通过systemd服务运行时,它会抛出这样的位置,无法打开数据库错误

/pythontut.db

我怀疑这是路径错误还是权限错误。可能如果有另一种路径设置方法。

系统文件:

[Unit]
Description=Main Jobs Running
After=graphical.target

[Service]
Type=simple
User=pi
ExecStart=/usr/bin/python /home/pi/pi-project/pi-main.py
Restart=on-abort

[Install]
WantedBy=graphical.target

【问题讨论】:

  • 您尚未设置起始目录。默认起始目录位于根目录 ("/"),这就是您所看到的。您可以在 systemd 文件中使用 WorkingDirectory 来设置所需的起始目录。
  • 另外,'pythontut.db' 是相对路径名。操作系统将自动添加当前工作目录。所以,你的 CWD os.path.join 并没有真正做任何事情。它可以被认为是防御性编程,以防其他模块不明智地更改 CWD,但这是其他人代码中的错误。

标签: python sqlite systemd os.path


【解决方案1】:

您应该编写代码,使其在执行时不依赖于当前工作目录。这样做是一种代码味道。当您知道文件相对于包含执行代码的文件的位置时,执行此操作的一种非常简单的方法如下:

# Get the directory containing this source file
code_directory = os.path.dirname(__file__)

# Relative path to get you from the directory contining your code
# to the directory containing the file you want to acceess.
relative_path = "../../some_directory"

# The name of the file you want to access
name_of_file_to_read = "somefile.txt"

# Compute the path to the file
file_path = os.path.join(code_directory, relative_path, name_of_file_to_read)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 2013-12-24
    • 2016-11-28
    • 2012-04-05
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    相关资源
    最近更新 更多