Getting os.environ to work with Python run via NSSM

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

When running Python scripts as a Windows service using NSSM (Non-Sucking Service Manager), you may encounter issues with os.environ not working as expected. This is because NSSM runs the service in a different environment compared to running it directly from the command line.

To resolve this issue, you can try one of the following approaches:

  1. Specify Environment Variables in NSSM: Configure the necessary environment variables directly in the NSSM service configuration. You can use the Environment tab in the NSSM GUI or the Environment command in the NSSM CLI to set the required environment variables explicitly.

  2. Load Environment Variables from an External File: Instead of relying on os.environ, you can load the environment variables from an external file within your Python script. Create a file (e.g., .env) with key-value pairs of the environment variables you need, and then load them using a package like python-dotenv or manually parse and set them in your script.

    Here's an example of using python-dotenv to load variables from a file:

    python
    from dotenv import load_dotenv
    import os

    # Load environment variables from .env file
    dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
    load_dotenv(dotenv_path)

    # Access environment variables
    value = os.getenv('MY_VARIABLE')

Ensure that you restart the NSSM service after making any changes to the configuration or environment variables.

By using one of these approaches, you should be able to make os.environ work properly with Python scripts running via NSSM as a Windows service.