简体   繁体   中英

Starting a python script on boot (startx) with an absolute path, in which there are relative paths

I realise this question may already exist, but the answers I've found haven't worked and I have a slightly different setup.

I have a python file /home/pi/python_games/frontend.py that I am trying to start when lxde loads by placing @python /home/pi/python_games/frontend.py in /etc/xdg/lxsession/LXDE/autostart .

It doesn't run and there are no error messages.

When trying to run python /home/pi/python_games/frontend.py , python complains about not being able to find the files that are loaded using relative links eg: /home/pi/python_games/image.png is called with image.png . Obviously one solution would be to give these resources absolute paths, but the python program also calls other python programs in its directory that also have relative paths, and I don't want to go changing all them.

Anyone got any ideas?

Thanks Tom

您可以在开始调用相对导入之前在脚本内更改当前工作目录,请使用os.chdir(“脚本所在的绝对路径”)。

Rather than change your current working directory, in your frontend.py script you could use the value of the predefined __file__ module attribute, which will be the absolute pathname of the script file, to determine absolute paths to the other files in the same directory.

Functions in the os.path module, such as split() and join() , will make doing this fairly easy.

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