简体   繁体   中英

How can I start and stop a Python script from shell

thanks for helping!

I want to start and stop a Python script from a shell script. The start works fine, but I want to stop / terminate the Python script after 10 seconds. (it's a counter that keeps counting). bud is won't stop.... I think it is hanging on the first line.

What is the right way to start wait for 10 seconds en stop?

Shell script:

python /home/pi/count1.py

sleep 10

kill /home/pi/count1.py

It's not working yet. I get the point of doing the script on the background. That's working!. But I get another comment form my raspberry after doing:

python /home/pi/count1.py & 

sleep 10; kill /home/pi/count1.py

/home/pi/sebastiaan.sh: line 19: kill: /home/pi/count1.py: arguments must be process or job IDs

It's got to be in the: (but what? Thanks for helping out!)

sleep 10; kill /home/pi/count1.py

You're right, the shell script "hangs" on the first line until the python script finishes. If it doesn't, the shell script won't continue. Therefore you have to use & at the end of the shell command to run it in the background. This way, the python script starts and the shell script continues.

The kill command doesn't take a path, it takes a process id. After all, you might run the same program several times, and then try to kill the first, or last one.

The bash shell supports the $! variable, which is the pid of the last background process.

Your current example script is wrong, because it doesn't run the python job and the sleep job in parallel. Without adornment, the script will wait for the python job to finish, then sleep 10 seconds, then kill.

What you probably want is something like:

python myscript.py &     # <-- Note '&' to run in background

LASTPID=$!               # Save $! in case you do other background-y stuff

sleep 10; kill $LASTPID  # Sleep then kill to set timeout.

You can terminate any process from any other if OS let you do it. Ie if it isn't some critical process belonging to the OS itself.

The command kill uses PID to kill the process, not the process's name or command.

Use pkill for that.

You can also, send it a different signal instead of SIGTERM (request to terminate a program) that you may wish to detect inside your Python application and respond to it.

For instance you may wish to check if the process is alive and get some data from it.

To do this, choose one of the users custom signals and register them within your Python program using signal module.

To see why your script hangs, see Austin's answer.

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