使用systemd自动启动Python3脚本时出错

时间:2018-08-12 14:53:56

标签: python-3.x systemd

到目前为止,我一直在运行带有屏幕的Python3脚本。但是,当我重新启动RPI时,这变得很烦人。因此,我创建了这个systemd文件:

[Unit]
Description=BME680_Wohnzimmer
After=multi-user.target

[Service]
Type=idle
ExecStart=/usr/bin/python3 /srv/scripts/bsec_bme680_linux/bsec_bme680.py

[Install]
WantedBy=multi-user.target

请求状态时,我得到:

    ● bme680_wohnzimmer.service - BME680_Wohnzimmer
   Loaded: loaded (/lib/systemd/system/bme680_wohnzimmer.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Sun 2018-08-12 11:59:47 UTC; 2h 45min ago
  Process: 1640 ExecStart=/usr/bin/python3 /srv/scripts/bsec_bme680_linux/bsec_bme680.py (code=exited, status=1/FAILURE)
 Main PID: 1640 (code=exited, status=1/FAILURE)

Aug 12 11:59:47 raspberrypi python3[1640]:   File "/srv/scripts/bsec_bme680_linux/bsec_bme680.py", line 7, in <module>
Aug 12 11:59:47 raspberrypi python3[1640]:     proc = subprocess.Popen(['./bsec_bme680'], stdout=subprocess.PIPE)
Aug 12 11:59:47 raspberrypi python3[1640]:   File "/usr/lib/python3.5/subprocess.py", line 676, in __init__
Aug 12 11:59:47 raspberrypi python3[1640]:     restore_signals, start_new_session)
Aug 12 11:59:47 raspberrypi python3[1640]:   File "/usr/lib/python3.5/subprocess.py", line 1282, in _execute_child
Aug 12 11:59:47 raspberrypi python3[1640]:     raise child_exception_type(errno_num, err_msg)
Aug 12 11:59:47 raspberrypi python3[1640]: FileNotFoundError: [Errno 2] No such file or directory: './bsec_bme680'
Aug 12 11:59:47 raspberrypi systemd[1]: bme680_wohnzimmer.service: Main process exited, code=exited, status=1/FAILURE
Aug 12 11:59:47 raspberrypi systemd[1]: bme680_wohnzimmer.service: Unit entered failed state.
Aug 12 11:59:47 raspberrypi systemd[1]: bme680_wohnzimmer.service: Failed with result 'exit-code'.

失败的行是:

proc = subprocess.Popen(['./bsec_bme680'], stdout=subprocess.PIPE)

通过“ sudo python3 bsec_bme680.py”运行此程序时,一切都很好。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

  

python3 [1640]:FileNotFoundError:[Errno 2]没有这样的文件或目录:   './bsec_bme680'

如果使用相对路径,则必须设置(systemd.exit(5)):

   WorkingDirectory=
       Takes a directory path relative to the service's root directory specified by RootDirectory=, or the special value "~". Sets the working directory for executed processes. If set to "~", the home
       directory of the user specified in User= is used. If not set, defaults to the root directory when systemd is running as a system instance and the respective user's home directory if run as user.
       If the setting is prefixed with the "-" character, a missing working directory is not considered fatal. If RootDirectory=/RootImage= is not set, then WorkingDirectory= is relative to the root of
       the system running the service manager. Note that setting this parameter might result in additional dependencies to be added to the unit (see above).

更好的解决方案:在服务中使用绝对路径。