Python – create an script which can be started and stoped manually

Advertisements

I’m new to python and looking for a solution to create a python *.py file which can be started from the terminal and which should do some logging into a file. The script should run, and perform logging into the file until I would stop it.
Of course there is a way to use the while True loop to run the code, but is there a fancy way to do this?

And the other question is how to listen for sys.args? For example I would start the script from the terminal with: ../python3 myFile.py and at this point the program starts and do the work. At a later time I would call something like ../python3 myFile.py stop. The script should get the arg=stop and perform sys.exit() to stop the execution.
Thanks

>Solution :

I tried to create your programm:

import time
import sys
import os

def programm():
    print("I'm running on", os.getpid()) # !! getpid return an int 
    i=0
    while True:
        time.sleep(1)
        print(i)
        i+=1


def kill_programm(pid): # !! pid is a string

    if "win" in sys.platform: # if it's windows
        os.system("taskkill /F /PID "+pid)
    else:
        os.system("kill - 9 "+pid) # I don't know if that works for other os


if len(sys.argv)== 1:
    programm()
elif len(sys.argv) == 3 and sys.argv[1] == "stop":
    kill_programm(sys.argv[2]) # * sys.argv return a list of string
else:
    print("Parameters invalid")

use:

run:
python programm.py

to kill the programm
run:

python programm.py stop <PID THAT THE PROGRAMM PRINT>

Leave a ReplyCancel reply