繁体   English   中英

如何正确设置 os.path。 由 systemd 服务运行时显示不同的路径

[英]How to set os.path correctly. Shows a different path when ran by systemd service

我有一个 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 中显示 output(Python 文件和数据库在同一个文件夹中)

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

但是当它通过systemd服务运行时,它会抛出 location like this with unable to opendb 错误

/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

你的文件是你程序的一部分吗? 也就是说,文件将始终与代码位于同一目录中吗? 如果是这样,则适用以下内容。 如果您在命令提示符下运行代码(即:您正在编写命令行工具),这是使用当前工作目录有意义的一种情况。 如果您正在查找配置文件或用户决定放置文件的其他位置,那么您应该以某种方式传递此文件的位置,例如作为命令行参数或通过代码知道的配置文件中的设置怎么找。

如果您要访问的文件相对于正在执行的代码始终位于同一位置,那么您应该编写代码,使其在执行时不依赖于当前工作目录(即:永远不要使用os.getcwd() ). 当您知道文件相对于包含执行代码的文件的位置时,执行此操作的一种非常简单的方法如下:

# 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)

如果您要访问的文件与您的代码位于同一目录中,则可以省略relative_path或将其设置为"." .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM