Sergio Sapiente
Sergio Sapiente

Reputation: 5

How to send command to python script?

I have a python script running in background via nohup.
It is an alarm system. Once I run the script it checks if a motion is detected. Now i have the problem of how to disable the alarm.
Could you help me to find a good way to send a command to disable/kill the running script?

Quick and dirty method was:
Checking a txt file content: if I want to shut down the script, I modify the txt.

Something like:

if txt content is "disable":
quit 

I am pretty new to python maybe you can help me.

Upvotes: 0

Views: 363

Answers (2)

Lily Mara
Lily Mara

Reputation: 4128

If you're using linux/unix/macos, you can kill the script from the command line

$ ps aux | grep python
nate     16210  0.2  0.0  20156  5176 pts/2    S+   17:02   0:00 python3
nate     16215  0.0  0.0   8044   932 pts/1    S+   17:02   0:00 grep python

The second field is the PID of the running process, kill it with the kill command:

$ kill 16210
$ ps aux | grep python
nate     16220  0.0  0.0   8044   932 pts/1    S+   17:02   0:00 grep python

To grab the pid automatically, you can add this to the top of your python script:

import os
pid = os.getpid()
with open('pid', 'w') as procfile:
    procfile.write(pid)

Now, you can grab that pid with one line of bash:

kill -TERM $(cat pid)

replace pid with the location of the file pid

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 113940

if os.path.exists(os.path.expanduser("~/disable_alarm.txt")):
     #then dont sound alarm

and just put a file in your home directoy when you want it disabled ...

Upvotes: 0

Related Questions