Run a python script in virtual environment from windows task scheduler

后端 未结 5 1719
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 20:48

I\'m trying to set up a recurring Python task through windows task scheduler.

I have had success when I input the path to \'python.exe\' and provide the script\'s pa

5条回答
  •  被撕碎了的回忆
    2020-12-03 21:39

    My solution is almost identical to mx0, but I've added an extra step to ensure environment parameters each time. Edit the path/to/app for the app_path variable.

    It may be a little redundant to check the environment setup every time, but I like ensuring my environment is set.

    Simply schedule the execute_app.bat file or run in the cmd prompt. Deactivate command is not needed unless running from an Anaconda prompt. If you use a full path for path/to/app this file can be executed from any directory. I also have a Linux solution using execute_app.sh file below from a terminal.

    This answer has been edited to simplify, and to use variables to make this easier to adapt to new projects.

    App structure:
    app/bin/app.py
    app/bin/execute_app.bat
    app/env/requirements.txt

    # execute_app.bat file
    # windows solution
    
    SETLOCAL
    set app_path=path/to/app
    set env_path=%app_path%/env
    set activ=%env_path%/Scripts/activate.bat
    set req=%env_path%/requirements.txt
    set app=%app_path%/bin/app.py
    
    py -m venv %env_path% && %activ% && python -m pip install --upgrade pip && pip install -r %req% && python %app%
    ENDLOCAL
    
    #!/bin/bash
    
    # execute_app.sh file
    # Linux solution
    
    app_path='path/to/app'
    env_path=$app_path'/env'
    activ=$env_path'/bin/activate'
    req=$env_path'/requirements.txt'
    app=$app_path'/bin/app.py'
    
    python3 -m venv $env_path &&
    . $activ &&
    python3 -m pip install --upgrade pip &&
    pip install -r $req &&
    python $app &&
    deactivate
    

提交回复
热议问题