开发者

Python - update configuration while running script

开发者 https://www.devze.com 2023-03-05 06:38 出处:网络
I have a python script which is constantly polling data. The script is constantly running and should never stop.

I have a python script which is constantly polling data. The script is constantly running and should never stop.

The script polls data from a track of keywords which are passed to it when the script is first run.

What would be the best way开发者_StackOverflow中文版 to update this track without stopping the script from another python script?

The only solution I can think of is to store the track in a txt file and check for any updates to the file on a set timer. Seems kind of messy.


It's better to encapsulate this settings file in a database. A simple SQLite DB file is enough - SQLite support is built-in with Python so no extra effort is required.

The advantage of a DB is that you won't run into race conditions of partially-written files, etc. The "configuration-adding" script adds keywords using a transaction, and the other script reading from the DB will only see it when it's wholly done. Just remember to not hold the DB open all the time in the periodic script. Once every some time, open it, read the keywords, and close it.


Polling a configuration-file is not messy, but a very common solution to this problem. You should go with it.


If you're using Linux you can try pyinotify. Example here.


I agree with track data stored in a file then use signal module to inform your script that new track data is ready ro be read, tie a function to, say SIGUSR1, and you're done, no risk of partially-written files.

In your script put:

import signal

signal.signal(signal.SIGUSR1, read_track_data)

then, (linux way but would be much different in Windows) just send signal to your script just after updating your track data file.

$kill -n 10 PID_OF_YOUR_SCRIPT


You can communicate both scripts using sockets

0

精彩评论

暂无评论...
验证码 换一张
取 消