监视并重新启动 python 的批处理

Batch that monitors and restarts a python

我正在尝试创建一个批处理程序,以便在 python 文件关闭或崩溃时重新启动它们,使用以下命令:

@echo off
:a
cd C:\Users\PC\Desktop\testfolder
test1.py
test2.py
test2.py
goto a

但是不起作用,我该怎么办?

我认为您的情况需要 "infinite loop" 和 python 文件的组合会使您的 CPU 超载。修改一段代码(仅适用于单个文件扩展名 (*.bat, *.txt))。请参阅下文了解更一般的内容。

@echo off
setlocal EnableExtensions

:start_python_files
start "1st" "test1.py"
start "2nd" "test2.py"
start "3rd" "test3.py"

:check_python_files
call:infinite 1st test1.py
call:infinite 2nd test2.py
call:infinite 3rd test3.py
goto:check_python_files

:infinite
tasklist /FI "WINDOWTITLE eq %1 - %2" | findstr /c:PID > nul
rem findstr /c:PID command added above to confirm that tasklist has found the process (errorlevel = 0). If not (errorlevel = 1).
if %errorlevel% EQU 1 (start "%1" "%2")

好吧,这种方式可能会持续一段时间,所以如果文件关闭(约 2-3 秒,具体取决于您的 CPU 过载)。

如果它不适合您,请通知我。我还没有 python 安装,我不知道它们打开时是如何命名的:)。

所以,既然你(好心???)要求完整的答案,让我解释一下我的代码:

  • 我启用扩展 (setlocal EnableExtensions) 来更改 call 命令如下:

CALL command now accepts labels as the target of the CALL. The syntax is:

CALL :label arguments

来自 call /? 命令。您应该在新的 cmd 中键入它以获取更多信息

  • 我用 start 命令指定了 window 标题,所以我的代码可以工作。在新的 cmd window.

  • 中输入 start /?
  • I call infinite 子例程向其发送参数(window 标题和文件名)。这些可以通过 %1(第一个参数)和 %2(第二个参数)访问。

  • infinite 子程序中,我搜索 window title (WINDOWTITLE) EQUAL (eq) 以格式化 window title - filename .即使它不存在 tasklist 也会 return errorlevel0 与消息:

INFO: No tasks are running which match the specified criteria.

因为这里PID字符串不存在(如果找到就会存在),我们用findstr来搜索。如果找到,errorlevel 将是 0。否则,它将是 1.

  • 如果errorlevel1,则表示未找到进程,即文件已关闭。因此,我们使用发送的参数 (start "window title (%1)" "filename (%2)").

  • 重新打开它
  • 因为我们已经 call 编辑了 infinite 子程序,在它结束后,我们将 return 到 check_python_files 子程序执行上述所有这些无限,直到用户终止或计算机关闭。

正如稍后在聊天中讨论的那样,当我们 运行 python 标准文件(使用 start "window title")时 window 标题将是 python.exe 的完整路径文件。我找到了修复它的方法:start cmd /c 命令。修改后的一段代码:

@echo off
setlocal EnableExtensions

:start_python_files
start "1st" "cmd /c test1.py"
start "2nd" "cmd /c test2.py"
start "3rd" "cmd /c test3.py"

:check_python_files
call:infinite 1st test1.py
call:infinite 2nd test2.py
call:infinite 3rd test3.py
goto:check_python_files

:infinite
tasklist /FI "WINDOWTITLE eq %1" | findstr /c:PID > nul
rem findstr /c:PID command added above to confirm that tasklist has found the process (errorlevel = 0). If not (errorlevel = 1).
if %errorlevel% EQU 1 (start "%1" "cmd /c %2")

我刚刚从 window 标题中添加了一个额外的 cmd /c(并删除了 %2),因为不需要它。

cmd /c 告诉系统 运行 一个新的 cmd 将执行字符串指定的命令,然后它会终止。

剧情简介:

  1. 命令应该是 运行 获取有关它们如何工作的更多信息:

    • call /?
    • start /?
    • goto /?
    • tasklist /?
    • findstr /?
    • cmd /?

我建议 运行 在一个全新的 cmd window 中执行以上操作 window。

  1. 一些有趣的参考资料:

真的很抱歉让你陷入这样的困境。不管怎样,谢谢你提供这么好的信息,让我明白我哪里错了。