简体   繁体   中英

Interactive python daemon

Is there a way to run a python that can process inputs interactively ? Without user input. That way methods can be called without needed to import and initialize the script.

What I have:

import very_heavy_package
very_heavy_package.initialize()

if very_heavy_package.check(input_file):
    do_something()
else:
    do_something_else()

I want something like:

import very_heavy_package
very_heavy_package.initialize()

@entry_point()
def check_something(input_file):
    if very_heavy_package.check(input_file):
        do_something()
    else:
        do_something_else()

import and initialize() lines take a very long time, but check_something() is pretty much instantaneous. I want to be able to check_something() multiple times on demand, without executing the full script all over.


I know this could be achieved with a server built in flask, but it seems a little overkill. Is there a more "local" way of doing this?

This example in particular is about running some Google Vision processing in an image from a surveillance camera on a Raspberry Pi Zero. Initializing the script takes a while (~10s), but making the API request is very fast(<100ms). I'm looking to achieve fast response time.

I don't think the webserver is overkill. By using an HTTP server with a REST api, you are using standards that most people will find easy to understand, use and extend. As an additional advantage, should you ever want to automate the usage of your tool, most automation tools already know how to speak REST and JSON.

Therefore, I would suggest you to follow your initial idea and use http.server or a library such as flask to create a small, no-frills web server with a REST api.

Try python -im your_module

The 'i' flag is for interactive and the 'm' flag is for module. And leave off the '.py'.

I have managed to solve my whim using signals. As I didn't need to pass any information, only trigger a function, that functionality solves my needs. So using signal python library and SIGUSR1

import signal
import time

import very_heavy_package
very_heavy_package.initialize()

def check_something():
    input_file = get_file()
    if very_heavy_package.check(input_file):
        do_something()
    else:
        do_something_else()

signal.signal(signal.SIGUSR1, check_something)

while True:
    # Waits for SIGUSR1
    time.sleep(600)

now I can start the daemon from bash with

nohup python myscript.py &

and make the wake up call with kill

pkill -SIGUSR1 -f myscript.py

Disclaimer : The pkill command is somewhat dangerous and it can have undesirable effects (ie killing a text editor with myscript.py opened). I should look into fancier ways of killing processes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM