修改:我已更新了我的问题和代码。
我正在从批处理文件中运行python脚本(在数百个文件上)。问题是,某些文件上的python脚本需要花费大量时间才能运行。我想要的是我的python脚本不应该在一个文件上运行超过5分钟。如果它需要超过5分钟,我只想杀死我正在运行的脚本并移动到下面的批处理文件代码中写入的下一个文件。
我想要的是,将300秒定义为我的代码可以在一个文件上花费的最长时间。如果超过300秒,批处理文件应该将其终止。但是,当它花费不到300秒时,它不应该等待300秒,而应立即转到下一个声明。
@echo off
setlocal enableextensions disabledelayedexpansion
echo FILE NO: 1
rem filename1 is not a variable name but the name of the file itself
start "Python" python "Code.py" filename1 var1 & call :timeoutProcess "python.exe" 300
start "Python" python "Code.py" filename1 var2 & call :timeoutProcess "python.exe" 300
echo FILE NO: 2
start "Python" python "Code.py" filename2 var1 & call :timeoutProcess "python.exe" 300
start "Python" python "Code.py" filename2 var2 & call :timeoutProcess "python.exe" 300
echo FILE NO: 3
start "Python" python "Code.py" filename3 var1 & call :timeoutProcess "python.exe" 300
start "Python" python "Code.py" filename3 var2 & call :timeoutProcess "python.exe" 300
echo FILE NO: 4
start "Python" python "Code.py" filename4 var1 & call :timeoutProcess "python.exe" 300
start "Python" python "Code.py" filename4 var2 & call :timeoutProcess "python.exe" 300
echo FILE NO: 5
start "Python" python "Code.py" filename5 var1 & call :timeoutProcess "python.exe" 300
start "Python" python "Code.py" filename5 var2 & call :timeoutProcess "python.exe" 300
.
.
.
.
.
.
.
echo FILE NO: 200
start "Python" python "Code.py" filename200 var1 & call :timeoutProcess "python.exe" 300
start "Python" python "Code.py" filename200 var2 & call :timeoutProcess "python.exe" 300
exit /b
:timeoutProcess process timeout [leave]
rem process = name of process to monitor
rem timeout = timeout in seconds to wait for process to end
rem leave = 1 if process should not be killed on timeout
for /l %%t in (1 1 %~2) do (
timeout /t 1 >nul
tasklist | find /i "%~1" >nul || exit /b 0
)
if not "%~3"=="1" taskkill /f /im "%~1" >nul
exit /b 1
如果我运行它直到filename5,这个代码完全正常。但是,当我将其运行到filename200时,此代码仅针对filename1运行,并且直接移至filename13,然后运行filename170。我无法理解这个问题。似乎没有任何语法错误。
我是编写批处理文件的新手。请帮助解决这个问题。如果你有更好的替代方案来解决这个问题(而不是超时),那么请告诉我。
P.S。:我也尝试在Eventlet包中使用Python中的Timeout函数,但是这个函数在我的文件上不能正常工作,因此我认为我应该尝试从批处理文件中超时。 我正在使用Windows机器并使用Python 2.7。
答案 0 :(得分:1)
也许最简单的方法是循环检查进程是否已经结束。如果过程结束,请离开循环。如果循环结束,则终止进程
@echo off
setlocal enableextensions disabledelayedexpansion
start "" python "E:\Code1.py"
call :timeoutProcess "python.exe" 300
start "" python "E:\Code2.py"
call :timeoutProcess "python.exe" 300
exit /b
:timeoutProcess process timeout [leave]
rem process = name of process to monitor
rem timeout = timeout in seconds to wait for process to end
rem leave = 1 if process should not be killed on timeout
for /l %%t in (1 1 %~2) do (
timeout /t 1 >nul
tasklist | find /i "%~1" >nul || exit /b 0
)
if not "%~3"=="1" taskkill /f /im "%~1" >nul 2>nul
if %errorlevel% equ 128 ( exit /b 0 ) else ( exit /b 1 )
(代码改编自previous answer)