0

My goal is to use this batch file to constantly check if the two python scripts are running. If any one of the script is not, it will run it. Is there a way to check this in a batch file? I tried:

SET pid_1=TASKLIST|find /i "..script1.py"
echo %pid_1%
SET pid_2=TASKLIST|find /i "..script1.py"
echo %pid_2%

It didn't work.

Do I have to add a function in both of the scripts to write their pid in a file and then let the batch file check if the process exist? Like this: Check to see if python script is running

Yang
  • 177
  • 4
  • 20
  • Possible duplicate of [Assign Command output to Variable in Batch file](https://stackoverflow.com/questions/16203629/assign-command-output-to-variable-in-batch-file) – aschipfl May 11 '18 at 13:13
  • As an alternative to capturing the output of the (piped) command line in a variable, check the [`ErrorLevel`](http://ss64.com/nt/errorlevel.html) of the [`find` command](http://ss64.com/nt/find.html), which is `0` if a match is encountered and `1` if not; and check out the filter (`/FI`) possibilities of [`tasklist`](http://ss64.com/nt/tasklist.html)... – aschipfl May 11 '18 at 13:15
  • @aschipfl Thanks. Is the method to return the pid correct? How can I make sure both of the scripts are running if the error level is 0? – Yang May 11 '18 at 13:18
  • 1
    Generally speaking, the better practice is to let your operating system's service management tools keep your script running, instead of trying to script/develop something to do that yourself. See [How do you run a Python script as a service in Windows?](https://stackoverflow.com/questions/32404/how-do-you-run-a-python-script-as-a-service-in-windows) -- services can be configured to auto-restart on failure, and you can directly ask Windows if they're running by name. – Charles Duffy May 11 '18 at 13:22
  • You don't `echo` the variable, just put it on a line on its own! and it should be `SET "pid_1=TASKLIST|find /i "..script1.py""` and `SET "pid_2=TASKLIST|find /i "..script1.py""` too. – Compo May 11 '18 at 13:23
  • Since the PID changes every time you won't need it; just filter for the process name or window title: `tasklist /FI "ImageName eq python.exe" /FI "WindowTitle eq ??" && python.exe ... script1.py`... – aschipfl May 11 '18 at 13:33

0 Answers0