Module Object Won't Update Until Code is Restarted

耗尽温柔 提交于 2021-01-29 13:13:17

问题


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.

I tried;

  • re importing Gio module

  • deleting the imported module and re importing it

  • calling the function from other python file

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.

My service file:

[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?

Thanks


回答1:


Adding:

os.execv("path/to/file", sys.argv)

does the trick, the script re-runs with a different PID, therefore updated results are detected and printed out.



来源:https://stackoverflow.com/questions/60037881/module-object-wont-update-until-code-is-restarted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!