[英]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
. 我有一个python文件
/home/pi/python_games/frontend.py
,我正在尝试通过将@python /home/pi/python_games/frontend.py
放在/etc/xdg/lxsession/LXDE/autostart
来启动lxde时启动的python文件。
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
. 尝试运行
python /home/pi/python_games/frontend.py
,python抱怨无法找到使用相对链接加载的文件,例如: /home/pi/python_games/image.png
用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. 显然,一种解决方案是为这些资源提供绝对路径,但是python程序还会在其目录中调用其他python程序,这些程序也具有相对路径,因此我不想更改所有路径。
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. 您可以在
frontend.py
脚本中使用预定义的__file__
模块属性的值(该脚本文件的绝对路径名)来确定同一目录中其他文件的绝对路径,而不必更改当前的工作目录。
Functions in the os.path
module, such as split()
and join()
, will make doing this fairly easy. os.path
模块中的函数,例如split()
和join()
,将使此操作相当容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.