背景
之前写的一个基金数据爬取的脚本需要部署在windows系统,需要一个启动、关闭脚本
通用bat代码实现:
@echo offTITLE "启动bat"
rem 需要处理的程序名
SET process_name="Snipaste.exe"
rem 存放进程id的文件用来判断进程是否已经启动
SET pid_file=pid.txtrem 如果进程已经启动
if exist %pid_file% (
TASKLIST /FO CSV /NH /FI "imagename eq %process_name% " > %pid_file%ECHO 'kill %process_name%'
FOR /F "delims=, tokens=2,3" %%a IN (%pid_file%) do (
SET /A pid=%%aTASKKILL /F /PID %pid%
)
DEL %pid_file%
) else (
rem 进程没有启动则启动程序
ECHO 'start and save %process_name% pid'
%activate_venv%CD %projectPath%%CMD_OPTION%TASKLIST /FO CSV /NH /FI "imagename eq %process_name% " > %pid_file%
)
bat启动python项目实现:
rem @echo offrem 激活python虚拟环境
SET "activate_venv=conda activate D:\work\envpy"
rem 项目根目录
SET "projectPath=CD D:\FundDataAnalysis"
rem 启动脚本命令
SET "CMD_OPTION=python main.py"rem 监控的进程名称
SET process_name="python.exe"
SET pid_file=pid.txtif exist %pid_file% (
TASKLIST /FO CSV /NH /FI "imagename eq %process_name% " > %pid_file%ECHO 'kill %process_name%'
FOR /F "delims=, tokens=2,3" %%a IN (%pid_file%) do (
echo %p_no%
TASKKILL /F /PID %%a
)
DEL %pid_file%
) else (
ECHO 'start and save %process_name% pid'%activate_venv%
echo %activate_venv%echo %projectPath%
%projectPath%echo %CMD_OPTION%
rem %CMD_OPTION%
REM start /B /MIN %CMD_OPTION%
TITLE "My Batch Script"
START "" %CMD_OPTION%
rem %CMD_OPTION%TASKLIST /FO CSV /NH /FI "imagename eq %process_name%" > %pid_file%
)