{"id":1601,"date":"2019-06-12T22:18:29","date_gmt":"2019-06-12T14:18:29","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=1601"},"modified":"2021-01-10T13:12:44","modified_gmt":"2021-01-10T05:12:44","slug":"how-to-use-nssm-to-run-a-python-3-application-as-a-windows-service-in-its-own-python-3-virtual-environment","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-use-nssm-to-run-a-python-3-application-as-a-windows-service-in-its-own-python-3-virtual-environment\/","title":{"rendered":"How to use NSSM to run a Python 3 application as a Windows Service in its own Python 3 virtual environment"},"content":{"rendered":"<p>If you want to run a Python 3 application as a Windows Service, then you are going to love <a href=\"https:\/\/nssm.cc\/\" rel=\"noopener noreferrer\" target=\"_blank\">NSSM<\/a>. Since NSSM handles the life cycle of a Windows Service for our Python 3 application, we can keep it platform agnostic. <\/p>\n<p>Previously, we saw <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-use-a-python-3-virtual-environment-in-windows-10\/\" rel=\"noopener noreferrer\" target=\"_blank\">how we can use a Python 3 virtual environment in Windows 10<\/a>. Given that, let's see how we can use NSSM to run a Python 3 application as a Windows Service in its own Python 3 virtual environment.<\/p>\n<h2>Creating a sample Python 3 application<\/h2>\n<p>In order to simplify this tutorial, let's attempt to run the <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-create-an-api-endpoint-that-generates-a-qr-code-image-with-python-3-flask-restplus-and-python-qrcode\/\" rel=\"noopener noreferrer\" target=\"_blank\">Python 3 Flask application with an API endpoint that generates a QR Code image<\/a> as a Windows Service.<\/p>\n<p>In addition to that, let us place <strong>requirements.txt<\/strong> and <strong>run_app.py<\/strong> into the <code>%systemdrive%%homepath%\\Documents\\qr-code-app<\/code> folder.<\/p>\n<h3>Contents of requirements.txt<\/h3>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\nflask-restplus==0.12.1\r\nPillow==6.0.0\r\nqrcode==6.1\r\n<\/pre>\n<h3>Contents of run_app.py<\/h3>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom flask import Flask, Blueprint, request, send_file\r\nfrom flask_restplus import Api, Namespace, Resource, fields\r\n# import library to help us with file IO\r\nfrom io import BytesIO\r\n \r\nimport os, qrcode\r\n \r\n# Create Flask app\r\napp = Flask(__name__)\r\n \r\n# Associate Api with Blueprint\r\napi_blueprint = Blueprint('API', __name__)\r\napi = Api(api_blueprint,\r\n    title='Api for QR code app',\r\n    version='1.0',\r\n    description='This is an API for QR code app',\r\n    # All API metadatas\r\n)\r\n \r\n# Create namespace for containing Qr Code related operations\r\nqrcode_namespace = Namespace('QrCode', description='Qr code related operations')\r\n# Specify uri of qrcode namespace as \/qrcode\r\napi.add_namespace(qrcode_namespace, path='\/qrcode')\r\n# Specify uri of api blueprint as \/api\r\napp.register_blueprint(api_blueprint, url_prefix='\/api')\r\n \r\n# Define input model\r\nqrcode_creation_input = qrcode_namespace.model('QRCode creation Input', {\r\n    'value': fields.String(required=True, description='The value that is supposed to be encoded into qrcode'),\r\n})\r\n \r\n \r\n# Define API endpoint for creating Qr Code image\r\n@qrcode_namespace.route('\/')\r\n@qrcode_namespace.doc('Creates a QRCode image based on a string value.')\r\nclass QrCodeRoot(Resource):\r\n \r\n    @qrcode_namespace.expect(qrcode_creation_input)\r\n    @qrcode_namespace.produces(&#x5B;'image\/png'])\r\n    @qrcode_namespace.response(200, description='Return QR Code png image file.')\r\n    @qrcode_namespace.response(400, description='Invalid input provided.')\r\n    def post(self):\r\n \r\n        # Get value to encode into QR Code\r\n        json_input = request.get_json()\r\n        value_to_turn_into_qrcode = json_input&#x5B;'value']\r\n \r\n        # Create qr code image and return it as HTTP response\r\n        pil_img = qrcode.make(value_to_turn_into_qrcode)\r\n        img_io = BytesIO()\r\n        pil_img.save(img_io, 'PNG')\r\n        img_io.seek(0)\r\n        return send_file(img_io, mimetype='image\/png')\r\n \r\n \r\nif __name__ == '__main__':\r\n    port = int(os.getenv(&quot;PORT&quot;, &quot;5678&quot;))\r\n    app.run(host='0.0.0.0', port=port)\r\n<\/pre>\n<h2>Preparing the virtual environment to run our Python 3 application<\/h2>\n<p>Before continuing on, be sure to go through the tutorial on <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-use-a-python-3-virtual-environment-in-windows-10\/\" rel=\"noopener noreferrer\" target=\"_blank\">how to use a Python 3 virtual environment in Windows 10<\/a>. After you had gone through the tutorial, you would have installed Python 3 on your Windows machine. In addition to that, you will understand how to create, activate and install dependencies into a virtual environment.<\/p>\n<h3>Creating the virtual environment to run our Python 3 application<\/h3>\n<p>Given these points, let us first create the virtual environment to run our Python 3 application. In order to do so, start a command prompt window and type in the following command:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\npython -m venv &quot;%systemdrive%%homepath%\\Documents\\qr-code-app-env&quot;\r\n<\/pre>\n<p>After the command completes, you will find the Python 3 virtual environment within the <code>%systemdrive%%homepath%\\Documents\\qr-code-app-env<\/code> folder.<\/p>\n<h3>Installing the application dependencies into the virtual environment<\/h3>\n<p>Next, activate your Python 3 virtual environment by running the following command:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\n&quot;%systemdrive%%homepath%\\Documents\\qr-code-app-env\\Scripts\\activate.bat&quot;\r\n<\/pre>\n<p>After your Python 3 virtual environment got activated, run the following command to install the Python dependencies for the application:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\npip install -r &quot;%systemdrive%%homepath%\\Documents\\qr-code-app\\requirements.txt&quot;\r\n<\/pre>\n<p>When the dependencies are installed, you will be able to run your Python application within the virtual environment.<\/p>\n<h2>Creating the <code>.bat<\/code> file to run our Python 3 application in its own virtual environment<\/h2>\n<p>At this point in time, you are ready to create a <code>.bat<\/code> file to start your application within the virtual environment. Given that, create a <code>run_app.bat<\/code> in the <code>%systemdrive%%homepath%\\Documents\\qr-code-app<\/code> folder with the following content:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\ncall ..\\qr-code-app-env\\Scripts\\activate.bat\r\ncall python run_app.py\r\n<\/pre>\n<h2>Downloading a copy of NSSM<\/h2>\n<p>After you had created the windows batch file to run the your Python application within the virtual environment, proceed to <a href=\"https:\/\/nssm.cc\/download\" rel=\"noopener noreferrer\" target=\"_blank\">download NSSM<\/a>. Save the <code>.zip<\/code> file and extract its content. After extracting the content, you will find a <code>nssm.exe<\/code> file inside the <code>win32<\/code> and <code>win64<\/code> folder. <\/p>\n<p>Depending on <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-determine-if-your-windows-10-iot-operating-system-is-32-bit-or-64-bit\/\" rel=\"noopener noreferrer\" target=\"_blank\">whether your Windows is 32 bit or 64 bit<\/a>, you will use the corresponding <code>nssm.exe<\/code> file to install your Python application as a Windows Service.<\/p>\n<p>For the purpose of this tutorial, let's assume that we want to use the <code>nssm.exe<\/code> in the <strong><code>C:\\nssm-2.24\\win64<\/code><\/strong> folder.<\/p>\n<h2>Run a command prompt instance as administrator<\/h2>\n<p>In order to avoid being prompted for administrator access for subsequent calls to <code>C:\\nssm-2.24\\win64<\/code>, let's run a command prompt instance as administrator. <\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/Finding-Command-Prompt-and-running-it-as-administrator-on-Windows-10.gif\" alt=\"Finding Command Prompt and running it as administrator on Windows 10\" \/><\/p>\n<p>We will run the subsequent commands in this command prompt instance.<\/p>\n<h2>Installing your Python application as a Windows Service with nssm.exe<\/h2>\n<p>Given that our nssm.exe is located in <code>C:\\nssm-2.24\\win64<\/code>, we can then use the following command to install our Python application as a Windows Service:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nC:\\nssm-2.24\\win64\\nssm install qrcodeapp &quot;%systemdrive%%homepath%\\Documents\\qr-code-app\\run_app.bat&quot;\r\n<\/pre>\n<p>When you run the command, NSSM will install your Python 3 application as a Windows Service.<\/p>\n<p>At this point in time, <strong>your Windows Service is not yet started<\/strong>.<\/p>\n<h2>Enabling log files for your Python 3 application<\/h2>\n<p>When you start your Windows Service at this point in time, it will not generate any log files when it runs.<\/p>\n<p>Therefore, let's configure it to channel application output to log files.<\/p>\n<p>In order to do so, first start <strong>NSSM service editor<\/strong> with the following command:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nC:\\nssm-2.24\\win64\\nssm edit qrcodeapp\r\n<\/pre>\n<p>After the command run, <strong>NSSM service editor<\/strong> will appear for enabling log files for your Python 3 application.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/nssm-2.24-service-editor-for-editing-qrcodeapp-written-in-Python-3-Flask.gif\" alt=\"nssm-2.24 service editor for editing qrcodeapp written in Python 3 Flask\"\/><\/p>\n<p>Given that, click on the <strong>I\/O<\/strong> tab and enter the paths that you want the log files to appear:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/nssm-2.24-service-editor-for-qrcodeapp-with-output-and-error-log-paths-set.gif\" alt=\"nssm-2.24 service editor for qrcodeapp with output and error log paths set\" \/><\/p>\n<p>Once you are done with that, click <strong>Edit service<\/strong>.<\/p>\n<h2>Starting your Python application as a Windows Service<\/h2>\n<p>In order to start the Windows Service for your Python application, run the following command:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nC:\\nssm-2.24\\win64\\nssm start qrcodeapp\r\n<\/pre>\n<p>Since <strong>Startup Type<\/strong> for the Windows Service is set to <strong>Automatic<\/strong>, our Python 3 Flask application will run automatically when we had started our Windows machine.<\/p>\n<h2>Further usages of NSSM<\/h2>\n<p>At this point in time, we will have fulfilled our goal of using NSSM to run a Python 3 application as a Windows Service in its own Python 3 virtual environment.<\/p>\n<p>In addition to what I had covered, the nssm.exe contains several other functionalities.<\/p>\n<p>In case you need to use other functionalities of NSSM, you can refer to <a href=\"https:\/\/nssm.cc\/usage\" rel=\"noopener noreferrer\" target=\"_blank\">NSSM usage page<\/a> for more information.<\/p>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-pP\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-pP&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-pP&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F1601&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>If you want to run a Python 3 application as a Windows Service, then you are going to love <a href=\"https:\/\/nssm.cc\/\" rel=\"noopener noreferrer\" target=\"_blank\">NSSM<\/a>. Since NSSM handles the life cycle of a Windows Service for our Python 3 application, we can keep it platform agnostic. <\/p>\n<p>Previously, we saw <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-use-a-python-3-virtual-environment-in-windows-10\/\" rel=\"noopener noreferrer\" target=\"_blank\">how we can use a Python 3 virtual environment in Windows 10<\/a>. Given that, let&#8217;s see how we can use NSSM to run a Python 3 application as a Windows Service in its own Python 3 virtual environment.<\/p>\n","protected":false},"author":1,"featured_media":1609,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[4],"tags":[652,226,233,586,181,347,21],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/nssm-2.24-service-editor-for-qrcodeapp-with-output-and-error-log-paths-set.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-pP","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/1601"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=1601"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/1601\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1609"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=1601"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=1601"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=1601"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}