簡體   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