run_the_race
run_the_race

Reputation: 2408

Python script within a Pipenv as a windows service with NSSM

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.

Upvotes: 4

Views: 3351

Answers (2)

Blue Three Wheeler
Blue Three Wheeler

Reputation: 179

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.

Upvotes: 3

run_the_race
run_the_race

Reputation: 2408

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.

Upvotes: 1

Related Questions