简体   繁体   中英

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

I have a python code with database file called pythontut.db (.py and db file on same folder). I used OS.path for path setting. When it is executed in thonny it works fine, I have created a systemd service to run at reboot. But at reboot, the path is different and throws 'unable to open database' error.

I tried setting path in pi-main.py like this

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

It shows output in thonny like this (Python file and DB are in same folder)

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

But when it runs via systemd service it throws location like this with unable to opendb error

/pythontut.db

I'm suspecting is it a path error or permission error. Probably if there is an another method for path setting.

Systemd file:

[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

Is your file a part of your program? That is, will it always be true that the file will be in the same directory as the code? If so, then the following applies. If you are running the code at a command prompt (ie: you are writing a command line tool), this is the one case where using the current working directory makes sense. If you are locating a configuration file or something else where the user decides where to put the file, then you should somehow pass in the location of this file, like as a command line parameter or via a setting in a configuration file that your code knows how to find.

If the file you want to access is always in the same place relative to the code being executed, then you should write your code so that it is not dependent on what the current working directory is when it executes (ie: never use os.getcwd() ). A very easy way to do this when you know where the file is relative to the file that contains the executing code is as follows:

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

If the file you want to access is in the same directory as your code, then you can leave out relative_path or set it to "." .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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