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:
- cd C:\pipenvfolder\foo
- 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:
- nssm.exe install ServiceName "C:\Users\Username\AppData\Local\Programs\Python\Python36\Scripts\pipenv.exe" "run python main.py"
- 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.
 
    