jsstuball
jsstuball

Reputation: 4931

Best way to communicate with Python script from command line?

I apologize if this is a duplicate but my search terms didn't find me what I was looking for.

I only ever 'kill' my python script using its linux process id.

This has served me well but now I need to pickle certain things right before terminating.

What is the best practice for communicating with a running Python script from the linux command line? Is there a library I should know about?

Example action would be sending a terminate command to the running script, but also can see uses in the near future for modifying config variables etc.

Upvotes: 1

Views: 340

Answers (3)

tripleee
tripleee

Reputation: 189517

There is no single best way. Depending on your requirements, you might choose between

  • Signals. A single signal can communicate a few bits of information (with one signal, one bit; with two signals, two bits, because you can choose which one yon send, etc) and it's one-way; but it's reasonably real-time and asynchronous, so excellent for quick and easy one-way communications, perhaps as out-of-band information in addition to, or on top of, something more complex.
  • Shared memory is quick and efficient two-way communications but nontrivial to use in practice, and obviously constrained to processes running on the same host.
  • Sockets are very versatile and reasonably efficient for communication over a network, and reasonable for moderate amounts of data even on the same host.

This is pretty U*x-centric; Windows programmers tend to use threading and thus shared memory IPC a lot more.

Upvotes: 1

Elbek
Elbek

Reputation: 646

kill command in linux/unix sends signal to the process and process handles signal (except SIGSTP and SIGKILL). So by saying killing process you are just sending SIGKILL signal.

So for better terminating the script you should use other signal (for example SIGINT this acts like pressing CTRL+C in terminal) and handling this signal by assigning signal handler in your script. For more info about signal handlers use this link.

By assigning signal handlers you can ignore signal or use your own custom action like: clean up process and exit or something else.

Upvotes: 1

Grisha
Grisha

Reputation: 453

One way would be to install signal handlers: https://docs.python.org/3/library/signal.html, for example, for SIGHUP (the hang up signal)

Upvotes: 2

Related Questions