python - python的Systemd服务没有在文件中写入数据
问题描述
我有一个 python 脚本,它检查网络状态并相应地将数据写入文件。下面是代码:
cmd = "ping -c 1 www.google.com"
res = (subprocess.call(cmd, shell=True))
if res == 0:
if os.path.exists('network.txt') == False:
#File is not present, create it (This will only happen for the 1st time)
log.error("Writing data to file")
f= open('network.txt', "w+")
f.write("online")
f.close()
else:
#File is present
log.error("Writing data to file")
f= open('network.txt', "w")
f.write("online")
f.close()
else:
if os.path.exists('network.txt') == False:
#File is not present, create it (This will only happen for the 1st time)
log.error("Writing data to file")
f= open('network.txt', "w+")
f.write("offline")
f.close()
else:
#File is present
log.error("Writing data to file")
f= open('network.txt', "w")
f.write("offline")
f.close()
time.sleep(1)
当我运行这段代码时,我可以看到脚本正在将数据写入online
文件。所以我为此创建了一个服务,它可以继续在后台运行并可以将数据写入文件。下面是服务:offline
network.txt
systemd
[Unit]
Description=log health of device on regular interval
[Service]
Type=simple
ExecStart=/usr/bin/python3 /home/pi/Documents/health.py
Restart=on-failure
RestartSec=30s
StandardOutput=null
[Install]
WantedBy=multi-user.target
当我启动服务时,我可以看到状态为正在运行,我也可以从日志中看到,Writing data to file
但没有数据写入文件。我还检查了使用ls-lh
它创建文件的时间不会改变。这意味着服务文件中有问题,不允许它写入文件,但在我看来一切正常。
谁能帮我确定这里的问题是什么?
解决方案
由于您的文件路径network.txt
是相对的,而不是绝对的,因此将从调用 python 脚本的位置(当前工作目录,cwd)创建文件。对于 systemd,这将是 root ( /
)。根据这个答案,您可以通过以下方式更改 systemd 中的 cwd
[Service]
WorkingDirectory=/your/path/here
您将在 中找到您的文件/your/path/here/network.txt
。
或者,在您的 python 脚本中使用绝对路径,file_path = "/your/path/here/network.txt"
. 用 替换所有出现"network.txt"
的file_path
。
更好的是,让它成为一个论点:
import sys
if len(sys.argv) > 1:
file_path = sys.argv[1]
else:
file_path = "/your/default/path"
file_name = file_path + "/network.txt"
network.txt
现在,您可以在调用脚本时选择放置文件的路径:
ExecStart=/usr/bin/python3 /home/pi/Documents/health.py /custom/path
推荐阅读
- python - 我可以使用 swagger 创建的服务器存根模型作为 sqlAlchemy 的模型吗?
- ios - 没有名为“FlutterPluginRegistrar”的类型或协议
- sql - 显示列的每个唯一值的日期范围(HIVE-QL 查询)
- angular - 调用 router.navigate 方法后 Angular 组件不起作用?
- excel - 我可以创建一个计算字段,如总数的百分比吗?
- ruby-on-rails - 将带有 ar_firebird_adapter 的 Firebird DB 表转储到 Rails schema.rb 中,但并非所有表都正确转储
- php - Vips 库线程限制
- reactjs - 尝试在使用 MUI 的 React 中使用 useState 对数组中的交替项目进行条件渲染 css
- flutter - 我的 Flutter 应用程序无法在 android studio 到 ios 模拟器上运行,因为 Command CompileSwift 因非零退出代码而失败
- ios - Ionic for IOS 与 Wordpress