4

Using How do you run a Python script as a service in Windows? I can get a python script to run as a service. Tested it with the following code I made:

import os
from time import sleep
from random import *
# import flask    <-- This line breaks it only when run from NSSM

count = 0
while True:
    num = randint(1, 10000)
    count+=1
    os.mkdir("C:\\temp\\" + str(count) + '_' + str(num))
    sleep(2)

I tested the executable and arguments to put into NSSM by first running the following:

  1. cd C:\pipenvfolder\foo
  2. C:\Users\Username\AppData\Local\Programs\Python\Python36\Scripts\pipenv.exe run python main.py

And it starts the script successfully, even if it has imports to packages installed in the pipenv (e.g. flask). I then created a NSSM service with:

  1. nssm.exe install ServiceName "C:\Users\Username\AppData\Local\Programs\Python\Python36\Scripts\pipenv.exe" "run python main.py"
  2. nssm set ServiceName AppDirectory "C:\pipenvfolder\foo"

And every 2 seconds it creates a directory in c:\temp. All is good. However now I wish to import one of the installed Pipenv packages, i.e. the flask package installed within the pipenv. So I added "import flask" to the test script above.

I then set up NSSM to have an error log and checked why it was failing to start, and it is failing to import the flask module:

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    import flask
ModuleNotFoundError: No module named 'flask'

The nssm service must be starting in the correct app directory or else it would not find main.py. Calling it from the correct directory is what specifies the pipenv. Hence I cannot figure out why the pipenv is not being used to run the script in the same way as when run via the command line.

run_the_race
  • 1,344
  • 2
  • 36
  • 62

2 Answers2

3

Create a batch file which calls your virtual environment. Get the virtualenv path:

pipenv --venv

service.bat

call path/to/.virtualenv/Scripts/activate.bat
call python main.py

Install the service with nssm which calls this batch file.

0

I doubt this is going to get any answers, but if someone else has the same issue. I got around the issueby making an exe using pyinstaller. It is fairly quick and easy to do. Then I passed the .exe into NSSM as the executable to be run.

run_the_race
  • 1,344
  • 2
  • 36
  • 62