{"id":538,"date":"2019-09-29T23:56:27","date_gmt":"2019-09-29T15:56:27","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=538"},"modified":"2021-06-04T11:42:38","modified_gmt":"2021-06-04T03:42:38","slug":"how-to-use-python-3-virtual-environments-to-run-python-3-applications-on-your-raspberry-pi","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-use-python-3-virtual-environments-to-run-python-3-applications-on-your-raspberry-pi\/","title":{"rendered":"How to use Python 3 virtual environments to run Python 3 applications on your Raspberry Pi"},"content":{"rendered":"<p>Whenever I am working on a Python 3 project, I will always use a Python 3 virtual environment for running that project. Therefore, I tend to do the same when it comes to <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-use-your-raspberry-pi-for-python-development\/\" rel=\"noopener\" target=\"_blank\">building Python 3 applications to run on a Raspberry Pi<\/a>. <\/p>\n<p>If you are looking to build Python 3 applications to run on your Pi, then you may find this article useful for you.<\/p>\n<h2>Why should we run our Python 3 application in a virtual environment on the Raspberry Pi?<\/h2>\n<p>Since a virtual environment helps us isolate Python dependencies within an application runtime, we will be able to run applications with conflicting dependencies on the same Raspberry Pi. <\/p>\n<p>Although we can use <a href=\"https:\/\/www.docker.com\/\" rel=\"noopener\" target=\"_blank\">Docker<\/a> to isolate our applications with containers, Python 3 virtual environments are more light-weight for Raspberry Pi.<\/p>\n<h2 id=\"install-python3-venv\">How to install python3-venv on your Raspbian<\/h2>\n<p>If <code>python3-venv<\/code> is not available on your Raspbian, then you will need to run the following command in a terminal program to install it:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nsudo apt-get install python3-venv -y\r\n<\/pre>\n<h2>Running the command to create a Python 3 virtual environment<\/h2>\n<p>However, if <a href=\"https:\/\/docs.python.org\/3\/library\/venv.html\" rel=\"noopener\" target=\"_blank\"><code>python3-venv<\/code><\/a> is available on your Raspberry Pi, then you can create a Python 3 virtual environment. For example, if I want to create a virtual environment within the <code>my_venv<\/code> directory in the home directory of the current user, then I will run the following command:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\npython3 -m venv ~\/my_venv\r\n<\/pre>\n<p>After the command had completed, a directory named as <code>my_venv<\/code> will be created in the  home directory of the current user.<\/p>\n<p>If you see the following output:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nThe virtual environment was not created successfully because ensurepip is not\r\navailable.  On Debian\/Ubuntu systems, you need to install the python3-venv\r\npackage using the following command.\r\n\r\n    apt-get install python3-venv\r\n\r\nYou may need to use sudo with that command.  After installing the python3-venv\r\npackage, recreate your virtual environment.\r\n\r\nFailing command: &#x5B;'\/home\/pi\/my_venv\/bin\/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']\r\n<\/pre>\n<p>then you will need to <a href=\"#install-python3-venv\">install python3-venv<\/a>.<\/p>\n<h3>What is inside the ~\/my_venv directory?<\/h3>\n<p>If you look into the directory that was created by the <code>python3-venv<\/code> module, you will find everything that is needed to make the terminal session run within an isolated Python 3 environment. Any Python 3 dependencies that are installed for this virtual environment will be contained within this directory.<\/p>\n<h2>How to activate the Python 3 virtual environment on your Raspberry Pi<\/h2>\n<p>Before you can do anything with that Python 3 virtual environment, you will need to activate it first. In order to activate the Python 3 virtual environment, you need to use the <code>source<\/code> command to load <code>activate.sh<\/code> into the current shell session:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nsource ~\/my_venv\/bin\/activate\r\n<\/pre>\n<p>After you had done so, you will notice that the shell prompt got appended with the name of your Python 3 virtual environment:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\n(my_venv) pi@raspberrypi:~ $ \r\n<\/pre>\n<p>This meant that the Python 3 virtual environment had been activated in your current terminal session. If you want to verify that, then you can run the following commands:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nwhich python\r\nwhich pip\r\n<\/pre>\n<p>When the commands complete, you should see the following output:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\n\/home\/pi\/my_venv\/bin\/python\r\n\/home\/pi\/my_venv\/bin\/pip\r\n<\/pre>\n<p>Notice that the two binaries came from the Python 3 virtual environment directory that you had just created.<\/p>\n<p>In addition to that, you can check the Python 3 dependencies that is included within your Python 3 virtual environment:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\npip list\r\n<\/pre>\n<p>When you do so, you may find output similar to the following:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nPackage       Version\r\n------------- -------\r\npip           18.1   \r\npkg-resources 0.0.0  \r\nsetuptools    40.8.0 \r\n<\/pre>\n<h2>How to install Python 3 dependencies into the virtual environment<\/h2>\n<p>Once you had activated your virtual environment, you can then install whatever dependencies that your Python 3 application will need with the <code>pip<\/code> command. For example, I can run the following command to install Flask into my virtual environment:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\npip install flask\r\n<\/pre>\n<p>After the command complete, you will then be able to run a Python 3 application that uses Flask to realise a web server on your Raspberry Pi. You can verify the pip installation with the following command:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\npip list\r\n<\/pre>\n<p>After the command had completed, you should find new entries in the output:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nPackage       Version\r\n------------- -------\r\nClick         7.0    \r\nFlask         1.1.1  \r\nitsdangerous  1.1.0  \r\nJinja2        2.10.1 \r\nMarkupSafe    1.1.1  \r\npip           18.1   \r\npkg-resources 0.0.0  \r\nsetuptools    40.8.0 \r\nWerkzeug      0.16.0 \r\n<\/pre>\n<h2>Running a Python 3 application within your virtual environment<\/h2>\n<p>Suppose that you had created a Python 3 script at <code>~\/run_app.py<\/code> with the following content:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nfrom flask import Flask\r\n\r\napp = Flask(__name__)\r\n\r\napp.route('\/')\r\ndef index():\r\n\treturn 'Welcome to my Flask server running on my Raspberry Pi', 200\r\n\r\napp.run('0.0.0.0', 12345)\r\n<\/pre>\n<p>When you want to run this application, you can use the <code>python<\/code> command from the virtual environment to do so:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\npython ~\/run_app.py\r\n<\/pre>\n<p>After you had ran the command, you should see the following output in your shell terminal:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\n * Serving Flask app &quot;run_app&quot; (lazy loading)\r\n * Environment: production\r\n   WARNING: This is a development server. Do not use it in a production deployment.\r\n   Use a production WSGI server instead.\r\n * Debug mode: off\r\n * Running on http:\/\/0.0.0.0:12345\/ (Press CTRL+C to quit)\r\n<\/pre>\n<p>Press CTRL+C to stop the Flask application.<\/p>\n<h2>Deactivating the virtual environment<\/h2>\n<p>When you want to exit from the virtual environment, you can run the following command:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\ndeactivate\r\n<\/pre>\n<p>After you had done so, the shell prompt returns back to how it was before you activate the virtual environment:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\npi@raspberrypi:~ $ \r\n<\/pre>\n<p>At this point in time, when you run the following commands:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nwhich python\r\nwhich pip\r\n<\/pre>\n<p>you may find the following output:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\n\/usr\/bin\/python\r\n<\/pre>\n<p>Since I am running this examples from Raspbian lite, the <code>pip<\/code> is not installed by default. Given these points, you can be sure that your current shell terminal had deactivated the Python 3 virtual environment<\/p>\n<h2>Summing up<\/h2>\n<p>In summary, you will typically go through the following steps to use Python 3 virtual environments to run your application on your Raspberry Pi:<\/p>\n<ul>\n<li>Use python3-venv module to create a directory which contain your Python 3 virtual environment.<\/li>\n<li>Use source command to load the activate script within the Python 3 virtual environment directory.<\/li>\n<li>Install any Python 3 dependencies that your application with need.<\/li>\n<li>Run your Python 3 application while the virtual environment is activated.<\/li>\n<li>Exit your virtual environment by using the deactivate script.<\/li>\n<\/ul>\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-8G\" 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-8G&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-8G&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%2F538&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>Whenever I am working on a Python 3 project, I will always use a Python 3 virtual environment for running that project. Therefore, I tend to do the same when it comes to <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-use-your-raspberry-pi-for-python-development\/\" rel=\"noopener\" target=\"_blank\">. <\/p>\n<p>If you are looking to build Python 3 applications to run on your Pi, then you may find this article useful for you.<\/p>\n","protected":false},"author":1,"featured_media":1776,"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":[226,233,586,240,412,255,682],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/Python-logo-on-Raspberry-Pi-logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-8G","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/538"}],"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=538"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/538\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1776"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=538"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=538"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=538"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}