问题描述
不太确定如何提问,所以我正在尝试打印插入驱动器的卷.
Not quite sure how to ask this, so I am trying to print plugged drives' volumes.
这是我的代码的简化版本:
Here is a simplified version of my code:
from gi.repository import Gio
from time import sleep
import importlib
import os
def check():
importlib.reload(Gio)
vm = Gio.VolumeMonitor.get()
volumes = vm.get_volumes()
print("Volumes: {}".format([i.get_name() for i in volumes]))
sleep(2)
while True:
check()
所以这段代码打印出插入的驱动器的卷.直到现在都没问题,但是,当我插入新设备或拔下当前设备时,列表不会更新.它不会检测更改.
So this code prints out plugged drives' volumes. No problem until now, however, when I plug a new device or unplug the current one, the list won't update. It does not detect the changes.
我试过了;
重新导入 Gio 模块
re importing Gio module
删除导入的模块并重新导入
deleting the imported module and re importing it
从其他python文件调用函数
calling the function from other python file
我想最终用这段代码做一个服务.我相信我可以使用 cron
来完成这项工作,但是,我正在努力使其作为一项服务工作.
I would like to make a service out of this code in the end. I believe I could make this work with cron
, however, I am trying to make it work as a service.
我的服务文件:
[Unit]
Description=Usbmount service
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=5
User=abc
ExecStart=/usr/bin/python3 /abc/myuser/usbmount.py
ExecStop=/usr/bin/python3 /abc/myuser/usbmount.py
[Install]
WantedBy=multi-user.target
关于如何解决这个问题有什么想法吗?
Any ideas about how to solve this?
谢谢
推荐答案
添加:
os.execv("path/to/file", sys.argv)
成功了,脚本使用不同的 PID 重新运行,因此检测到更新的结果并打印出来.
does the trick, the script re-runs with a different PID, therefore updated results are detected and printed out.
这篇关于模块对象在代码重新启动之前不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!