<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sourav De on Medium]]></title>
        <description><![CDATA[Stories by Sourav De on Medium]]></description>
        <link>https://medium.com/@SrvZ?source=rss-435b363fb359------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ptcuNx_AEOn8bd6rx0vFhg.jpeg</url>
            <title>Stories by Sourav De on Medium</title>
            <link>https://medium.com/@SrvZ?source=rss-435b363fb359------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:47:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@SrvZ/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Proxmon: A Simple TUI to Monitor and Manage Your Proxmox Cluster]]></title>
            <link>https://medium.com/@SrvZ/proxmon-a-simple-tui-to-monitor-and-manage-your-proxmox-cluster-27174c404694?source=rss-435b363fb359------2</link>
            <guid isPermaLink="false">https://medium.com/p/27174c404694</guid>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[proxmox]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sourav De]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 20:26:32 GMT</pubDate>
            <atom:updated>2025-05-11T07:23:24.933Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lyfzbxADoWQfrV4p4ppvQg.png" /></figure><p>If you’re running a Proxmox VE cluster in your homelab or production environment — or if you’re reading this, you probably are (or planning to) — you already know how powerful the platform is. Proxmox offers excellent tools like pvesh, qm, and a solid web interface for managing your virtual machines and containers.</p><p>However, I always found myself wishing for something more native to my work style—a proper CLI tool that lets me manage everything <strong>directly from the terminal</strong> without constantly reaching for the mouse.</p><p>That’s precisely why I built <a href="https://github.com/Sr-vZ/Proxmon"><strong>Proxmon</strong></a> — a TUI (Text User Interface) powered by Python, Rich, and Textual that makes it effortless to <strong>monitor and manage Proxmox VMs and LXCs directly from your terminal. </strong>No more jumping between browser tabs, parsing JSON frompvesh, or writing custom bash scripts. Proxmon gives you a polished, real-time view of your infrastructure where you need it.</p><h3>🚀 What is Proxmon?</h3><p>Proxmon is a Python-based TUI that interfaces with the Proxmox API to give you a powerful and elegant way to:</p><ul><li>View real-time metrics of all VMs and containers</li><li>Start, stop instances</li><li>Navigate across nodes, types (VM or LXC), and statuses</li><li>Run the whole thing inside your terminal — perfect for SSH sessions and headless setups</li></ul><p>Think <strong>htop</strong>, but for Proxmox.</p><p>Thanks to <strong>Rich</strong> and <strong>Textual</strong>, the UI is modern, responsive, and visually appealing — with live-updating metrics, colored status indicators, and intuitive keybindings.</p><h3>🎨 UI Walkthrough</h3><p>Here’s what you get when you launch Proxmon:</p><ul><li><strong>Live Dashboard</strong>: A constantly updating table of your VMs and containers, with stats like CPU%, memory usage, and uptime.</li><li><strong>Color-Coded Status</strong>: Instantly spot running, stopped machines at a glance.</li><li><strong>Command Palette</strong>: Quickly start and stop machines with keyboard shortcuts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pQc0PFpls2OVAIsn8Yz14g.gif" /></figure><h3>🛠️Features at a Glance</h3><p>The features available currently on Proxmon:</p><p>✅ <strong>Live metrics</strong>: Real-time CPU, memory, disk usage stats</p><p>✅ <strong>VM/LXC management</strong>: Start, stop, reboot actions via keyboard</p><p>✅ <strong>API-powered</strong>: All data comes from the Proxmox API</p><p>✅ <strong>Built with Rich/Textual</strong>: Clean, modern terminal UI</p><p>✅ <strong>Lightweight &amp; fast</strong>: Perfect for low-resource servers and headless environments</p><h3>🐍 Under the Hood: The Tech Stack</h3><p>Proxmon is written entirely in <strong>Python</strong>, and leverages:</p><ul><li><a href="https://github.com/Textualize/rich"><strong>Rich</strong></a> for elegant, styled console output</li><li><a href="https://github.com/Textualize/textual"><strong>Textual</strong></a> for building the interactive TUI components</li><li><strong>Proxmox API</strong> for pulling in data and performing actions</li><li>A config (more precisely, ENV) file for authentication and node info</li></ul><h3>⚡ Getting Started</h3><h4>Step 1: Clone the Repo</h4><pre>git clone https://github.com/Sr-vZ/Proxmon.git<br>cd Proxmon</pre><h4>Step 2: Install Dependencies</h4><p>I recommend using a virtual environment:</p><pre>python3 -m venv venv<br>source venv/bin/activate<br>pip install -r requirements.txt</pre><h4>Step 3: Configure Access</h4><p>Create a .env file with your Proxmox API credentials:</p><pre>PROXMOX_HOST=&#39;https://&lt;PROXMOX-IP&gt;:8006&#39;<br># generate API keys from UI<br>TOKEN_ID=&#39;&lt;token-id&#39;<br>TOKEN_SECRET=&#39;&lt;token-secret&gt;&#39;<br># pve is default<br>NODE =&#39;&lt;node-name&gt;&#39;<br># SSH is required to run some commands <br># which is not possible via Proxmox API<br>SSH_HOST= &#39;&lt;PROXMOX-IP&gt;&#39;<br>SSH_USER=&#39;&lt;admin-user&gt;&#39;<br>SSH_PASSWORD=&#39;&lt;admin-user-password&gt;&#39;<br># Mention different port if not using default<br>SSH_PORT=&#39;22&#39;<br># if want to use keys instead of User/Pass<br>SSH_KEY=&#39;&lt;ssh-key&gt;&#39;</pre><h4>Step 4: Launch the App</h4><pre>python proxmon.py</pre><h3>🗺️Roadmap</h3><p>Proxmon is still evolving. Some upcoming features I’m exploring:</p><ul><li>🔐 <strong>SSH passthrough</strong>: Launch a shell directly into your VM/LXC</li><li>🧱 <strong>VM/LXC creation</strong>: Create machines directly from the CLI</li><li>📦 <strong>PyPI packaging</strong>: Install with a simple pip install proxmon</li></ul><p>If you want to contribute, feel free to <a href="https://github.com/Sr-vZ/Proxmon">star the repo</a>, fork it, or open an issue.</p><p>If you enjoyed this article and want to support what I’m building, feel free to <strong>follow me here on Medium</strong>, <strong>subscribe to my newsletter</strong>, or <strong>connect with me on </strong><a href="https://twitter.com/SrvzBlogs"><strong>Twitter</strong></a> for more updates.</p><p>If Proxmon made your homelab life a little easier and you’d like to show some love, you can always <a href="#"><strong>buy me a coffee</strong></a> — every bit helps fuel future projects like this one ☕🚀</p><figure><a href="https://ko-fi.com/srvzblogs"><img alt="" src="https://cdn-images-1.medium.com/max/286/0*irjHqbFuhMorDpvk.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27174c404694" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Halloween-Themed NeoPixel Clock with ESP8266 and NTP Time Sync]]></title>
            <link>https://medium.com/@SrvZ/spooky-pixels-build-a-diy-halloween-themed-clock-with-esp8266-and-neopixel-matrix-e843c5dc71c5?source=rss-435b363fb359------2</link>
            <guid isPermaLink="false">https://medium.com/p/e843c5dc71c5</guid>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[led]]></category>
            <category><![CDATA[halloween]]></category>
            <category><![CDATA[decoration]]></category>
            <category><![CDATA[arduino]]></category>
            <dc:creator><![CDATA[Sourav De]]></dc:creator>
            <pubDate>Thu, 31 Oct 2024 15:59:00 GMT</pubDate>
            <atom:updated>2025-07-25T17:17:21.160Z</atom:updated>
            <content:encoded><![CDATA[<p>I had two ESP8266 boards lying around for months, collecting dust as I ordered them, and completely forgot about them. With Halloween around the corner, I thought, why not give my workspace a spooky glow-up with a Halloween-themed clock that does more than tell the time? I imagined eerie messages, icons like pumpkins and ghosts, and telling time in between.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FVmAmDtl3HsDq5_a" /><figcaption>Photo by <a href="https://unsplash.com/@andyjh07?utm_source=medium&amp;utm_medium=referral">Andy Holmes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you want to build something similar and treat yourself, I’ll walk you through setting up the hardware, writing the code, and getting those colorful animations and texts running!</p><h3>First the Hardware and other requirements:</h3><ul><li><strong>ESP8266 (NodeMCU)</strong> — This microcontroller is WiFi-enabled, making it perfect for IoT and animated displays.</li><li><strong>8x8 NeoPixel Matrix</strong> — An RGB LED matrix is the heart of this project, creating vibrant light animations. I had two of them so it was in 8x16 configuration you can add more and any WS2811/2812 would work!</li><li><strong>5V Power Supply</strong> — NeoPixels can be power-hungry, so a stable power source is essential. I had no issues running two of the Neopixel from USB cable however I lowered the pixel brightness. For full brightness best adding a 5v 2A power supply.</li><li><strong>Jumper Wires</strong> and <strong>Breadboard</strong> (optional) — For connecting components.</li><li><strong>Micro-USB Cable</strong> — For programming and power.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Ob96QshJUqJytuQqMPhO9Q.jpeg" /><figcaption>CJMCU 64 Bit 8x8 WS2812 5050 RGB LED Driver Development Board</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*yCgXlDCggRCyvE728zVX9g.jpeg" /><figcaption>ESP8266 Nodemcu</figcaption></figure><h3>Setting up the Hardware:</h3><p>The CJMCU 64 Bit 8x8 WS2812 5050 RGB LED Driver Development Board which is the Neopixel Matrix in my case sometimes comes with male and female headers attached and some without it, mine was without any header so be prepared to do a little bit soldering the headers to the board.</p><p><strong>Power Connection</strong></p><ul><li>Connect the NeoPixel’s power pin (5V) to the ESP8266’s Vin pin or any 3v3 pin. Make sure to match ground (GND) connections between the ESP8266 and the NeoPixel matrix.</li></ul><p><strong>Data Line Connection</strong></p><ul><li>Connect the data input of the NeoPixel matrix to one of the ESP8266’s GPIO pins (e.g., D2). This will be the control pin for animations.</li></ul><p><strong>Prepare the Power Supply</strong></p><ul><li>If your matrix requires more power than the ESP8266 can supply, connect an external 5V power supply, remembering to connect all grounds.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Fx7XCwV6OlTs6jv1z-9Jg.jpeg" /></figure><h3>Programming the ESP8266:</h3><p>You’ll need the Arduino IDE and a few libraries to start:</p><h4><strong>Install the Required Libraries:</strong></h4><ul><li>Install the <strong>Adafruit NeoPixel</strong> library to control the LEDs.</li><li>Install <strong>ESP8266 board support</strong> via the Arduino IDE’s board manager.</li></ul><h4><strong>Code Setup</strong></h4><pre>#include &lt;ESP8266WiFi.h&gt;<br>#include &lt;WiFiUdp.h&gt;<br>#include &lt;Adafruit_GFX.h&gt;<br>#include &lt;Adafruit_NeoMatrix.h&gt;<br>#include &lt;Adafruit_NeoPixel.h&gt;<br>#include &lt;NTPClient.h&gt;<br><br>// WiFi credentials<br>const char* ssid = &quot;ADD YOUR WIFI SSID&quot;;<br>const char* password = &quot;YOUR WIFI Password&quot;;<br><br>// NTP client setup<br>WiFiUDP ntpUDP;<br>// NTPClient timeClient(ntpUDP, &quot;pool.ntp.org&quot;, 0, 60000); // Adjust the offset as needed<br><br><br>// NeoMatrix configuration<br>#define PIN D2 // Change to the pin you&#39;re using<br>#define MATRIX_WIDTH 16<br>#define MATRIX_HEIGHT 8<br>#define MATRIX_TYPE (NEO_MATRIX_BOTTOM + NEO_MATRIX_RIGHT + NEO_MATRIX_COLUMNS + NEO_MATRIX_ZIGZAG)<br><br>Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(MATRIX_WIDTH, MATRIX_HEIGHT, PIN,<br>  NEO_MATRIX_TOP     + NEO_MATRIX_RIGHT +<br>  NEO_MATRIX_COLUMNS + NEO_MATRIX_PROGRESSIVE,<br>  NEO_GRB            + NEO_KHZ800);<br><br>// Colors<br>uint16_t color = matrix.Color(0, 150, 0); // Green<br><br>// Scrolling variables<br>int xPos = MATRIX_WIDTH; // Start off-screen<br>int textWidth;<br><br>// Colors<br>uint16_t orange = matrix.Color(255, 69, 0);<br>uint16_t black = matrix.Color(0, 0, 0);<br>uint16_t green = matrix.Color(0, 255, 0);<br>uint16_t white = matrix.Color(255, 255, 255);<br><br>// Pumpkin shape<br>const uint8_t pumpkin[8][8] = {<br>  {0, 0, 1, 1, 1, 1, 0, 0},<br>  {0, 1, 1, 1, 1, 1, 1, 0},<br>  {1, 1, 0, 1, 1, 0, 1, 1},<br>  {1, 1, 1, 1, 1, 1, 1, 1},<br>  {1, 0, 1, 1, 1, 1, 0, 1},<br>  {1, 1, 0, 0, 0, 0, 1, 1},<br>  {0, 1, 1, 1, 1, 1, 1, 0},<br>  {0, 0, 1, 1, 1, 1, 0, 0}<br>};<br><br>// Ghost shape<br>const uint8_t ghost[8][8] = {<br>  {0, 0, 1, 1, 1, 1, 0, 0},<br>  {0, 1, 1, 1, 1, 1, 1, 0},<br>  {1, 1, 0, 1, 1, 0, 1, 1},<br>  {1, 1, 1, 1, 1, 1, 1, 1},<br>  {1, 1, 1, 1, 1, 1, 1, 1},<br>  {1, 1, 1, 1, 1, 1, 1, 1},<br>  {1, 1, 1, 1, 1, 1, 1, 1},<br>  {1, 0, 1, 0, 1, 0, 1, 1}<br>};<br><br><br>// Display shape on the NeoMatrix<br>void displayShape(const uint8_t shape[8][8], uint16_t color, int xOffset) {<br>  matrix.fillScreen(black);<br>  for (int y = 0; y &lt; 8; y++) {<br>    for (int x = 0; x &lt; 8; x++) {<br>      if (shape[y][x] == 1) {<br>        matrix.drawPixel(x + xOffset, y, color);<br>      }<br>    }<br>  }<br>  matrix.show();<br>  delay(100);<br>}<br><br><br>// Scroll shapes (Pumpkin and Ghost) across the screen as surprise animation<br>void scrollShapes() {<br>  <br>  for (int x = MATRIX_WIDTH; x &gt;= -8; x--) {  // Scroll from right to left<br>    displayShape(pumpkin, orange, x);       // Display pumpkin on the left<br>    delay(100);<br>  }<br>  <br>  for (int x = 0; x &lt;= MATRIX_WIDTH; x++) {  // Scroll from left to right<br>    displayShape(ghost, white, x);      // Display ghost on the left<br>    delay(100);<br>  }<br>  <br>  matrix.fillScreen(0);<br>}<br><br>void displayTime(){<br>    // Update time<br>  timeClient.update();<br><br>  // Get hours and minutes in 24-hour format<br>  int hours = timeClient.getHours();<br>  int minutes = timeClient.getMinutes();<br><br>  // Format time as HH:MM<br>  String formattedTime = (hours &lt; 10 ? &quot;0&quot; : &quot;&quot;) + String(hours) + &quot;:&quot; +<br>                         (minutes &lt; 10 ? &quot;0&quot; : &quot;&quot;) + String(minutes);<br><br>  // Clear the matrix display<br>  matrix.fillScreen(0);<br><br>  // Set cursor position for scrolling text<br>  matrix.setCursor(xPos, 0); // Start scrolling horizontally across the matrix<br>  color = matrix.Color(random(0,255), random(0,255), random(0,255)); // random color<br>  matrix.setTextColor(color);<br>  matrix.print(formattedTime);<br><br>  // Show the matrix display<br>  matrix.show();<br><br>  // Move the text position to the left<br>  xPos--;<br><br>  // Reset position once text has scrolled off screen<br>  if (xPos &lt; -matrix.width()) {<br>    xPos = MATRIX_WIDTH;<br>  }<br><br>  // Delay for smooth scrolling speed<br>  delay(200);<br>}<br><br>void setup() {<br>  // Initialize Serial Monitor<br>  Serial.begin(115200);<br><br>  // Initialize NeoMatrix<br>  matrix.begin();<br>  matrix.setTextWrap(false);<br>  matrix.setBrightness(8); // Adjust as needed<br>  matrix.setTextColor(color);<br><br>  // Connect to Wi-Fi<br>  Serial.print(&quot;Connecting to WiFi...&quot;);<br>  WiFi.begin(ssid, password);<br>  while (WiFi.status() != WL_CONNECTED) {<br>    delay(500);<br>    Serial.print(&quot;.&quot;);<br>  }<br>  Serial.println(&quot;Connected!&quot;);<br><br>  // Initialize time client<br>  timeClient.begin();<br>}<br><br><br><br>void loop() {<br><br>  static unsigned long lastAnimationTime = 0;<br>  unsigned long currentMillis = millis();<br>  displayTime();<br>  // Every 15-30 seconds, show the surprise Halloween animation<br>  if (currentMillis - lastAnimationTime &gt; random(30000, 60000)) {<br>    scrollShapes();<br>    lastAnimationTime = currentMillis;  // Reset the timer<br><br>  }<br>}</pre><p>The time is synced through ntp updates which requires an active internet connectivity. We are connecting to Wifi and getting the time updates and showing the same on NeoPixel matrix.</p><p>The Led driver side communication is being handled by the Adafruit libraries. There is another alternative library FastLED which is little bit better in terms of memory efficiency and faster calculations but I had issues working with it on my Nodemcu unit so I used the Adafruit libraries.</p><p>Here’s a little demo of the end result!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*FONlG6iqnWaajN6CN2tBuQ.gif" /></figure><p>If you enjoyed this article and would like to see more of such projects/posts and want to support or encourage me, feel free to follow me or subscribe to my newsletter, or follow me on <a href="https://twitter.com/SrvzBlogs">Twitter</a>.</p><p>Also if you want to support my blogging endeavor, you can buy me a coffee!</p><figure><a href="https://ko-fi.com/srvzblogs"><img alt="" src="https://cdn-images-1.medium.com/max/286/0*GHcWZXh_EdgVOvie.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e843c5dc71c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your APIs: A Guide to Python-Based Load Testing]]></title>
            <link>https://medium.com/@SrvZ/supercharge-your-apis-a-guide-to-python-based-load-testing-dd42663e1b17?source=rss-435b363fb359------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd42663e1b17</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[locust]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Sourav De]]></dc:creator>
            <pubDate>Sat, 21 Oct 2023 12:28:43 GMT</pubDate>
            <atom:updated>2023-10-21T12:28:43.030Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N_vI8kbcLTjfpgeB" /><figcaption>Photo by <a href="https://unsplash.com/@julianhochgesang?utm_source=medium&amp;utm_medium=referral">Julian Hochgesang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Very recently I was demonstrating an API for a particular backend to some extended team members. After the demo was completed someone from the attendees asked all the functions are well and good but how much load will it be able to handle in real-time scenario. At that time I wasn’t prepared for that and obviously couldn’t give a proper answer.</p><p>We develop and overengineer our APIs all the time but most of the times forget to test how will perfrom in real world scenarios. Some developers and engineers (the responsible ones ) do write some unit tests to check any functional errors however that doesn’t ensure when the API is deployed in production it will work as intended under a real-time load.</p><p>The solution is to do a loadtesting to check if there are any errors occuring due to high traffic also figure out strategies to circumvent those issues.</p><p>Most popular loadtesting framework for this type of requirement is JMeter. It’s a very good open-source tool written in Java and and my extensive experience in Java, which is absolutely non-existent, has me coding everything with Python instead! Genius, right? 😄</p><p>Well using JMeter is out of the window for me! But I have to provide the metrics for the API built so after some searching I came across Locust a Python based load testing module and my lifesaver in this case.</p><p>(Disclaimer: Actually there is no issues with using JMeter with a Python backend and they can be integrated with some effort.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JoJ-1LRdo0tNxqTE" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The Importance of Load Testing APIs</p><p>Before diving into Locust let’s understand why load testing APIs is crucial. When an API is deployed, it may encounter thousands or even millions of requests from various clients simultaneously. Without adequate testing, unforeseen issues may arise, such as slow response times, server crashes, or excessive resource consumption. Load testing allows developers to:</p><ol><li>Assess Performance: Load testing helps determine how well an API performs under different levels of user traffic, enabling developers to identify potential performance bottlenecks.</li><li>Evaluate Scalability: It’s essential to know how an API scales as user traffic increases. Load testing helps gauge whether the system can handle increased loads without compromising on response times.</li><li>Identify Weaknesses: Load testing exposes potential weaknesses and limitations in an API, which can then be addressed to enhance reliability and stability.</li><li>Reduce Downtime: By proactively identifying and fixing issues, load testing minimizes the risk of unexpected downtime during peak usage periods.</li></ol><p>Getting Started with Locust</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVV586vGqaJSCHeGpN1qUg.png" /><figcaption>Locust web interface</figcaption></figure><p>Let’s take a step-by-step approach to getting started with Locust and running a basic API load test:</p><p>Step 1: Install Locust To install Locust, make sure you have Python installed, and then use the Python package manager, pip, to install Locust:</p><pre>pip install locust</pre><p>Step 2: Create a Mock API with FastAPI Before we begin load testing, we need an API to test. For this purpose, we’ll create a simple mock API using FastAPI, a modern, fast, web framework for building APIs with Python.</p><pre>from fastapi import FastAPI<br>app = FastAPI()<br>@app.get(&quot;/api/endpoint&quot;)<br>def read_item():<br>    return {&quot;message&quot;: &quot;Hello, World!&quot;}</pre><p>Save the above code in a file named app.py.</p><p>Step 3: Run the FastAPI Server Open a terminal, and navigate to the directory containing app.py, and execute the following command:</p><pre>uvicorn app:app --reload</pre><p>This command starts the FastAPI server, and you can access the API by visiting http://localhost:8000 in your web browser.</p><p>Step 4: Writing a Simple Load Test Create another Python file, e.g., api_load_test.pyand import the necessary modules:</p><pre>from locust import HttpUser, task, between<br>class APIUser(HttpUser):<br>    wait_time = between(1, 3)<br>    @task<br>    def call_api_endpoint(self):<br>        self.client.get(&quot;/api/endpoint&quot;)</pre><p>In this example, we define a APIUser class that inherits from HttpUser, representing a user in our load test. The @task decorator defines the user&#39;s behavior, which is to send a GET request to the specified API endpoint.</p><p>Step 5: Run the Load Test Open a new terminal, and navigate to the directory containing api_load_test.py, and execute the following command:</p><pre>locust -f api_load_test.py</pre><p>This command starts the Locust web interface, and you can access it by visiting http://localhost:8089 in your web browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AheWbZ64qOTY9e7FZ74jjg.png" /></figure><p>From there, you can specify the number of users to simulate and the hatch rate (number of users spawned per second).</p><p>Step 6: Analyze Results As the test runs, the Locust web interface provides real-time insights into the number of requests per second, response times, and any failures that may occur during the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXyT2dpVuDWTb1HFPms-ug.png" /><figcaption>Demo test execution (from locust docs)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/0*FFJ4Fcv-AZdGhY23.png" /><figcaption>Demo test execution load curve (from locust docs)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/0*gMjwUhQuUkYNRyBY.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/0*e_Nq2KEWlag1cGks.png" /></figure><p>Conclusion</p><p>Load testing is a critical aspect of API development and ensures that your APIs can handle high-traffic loads without compromising performance. Locust is one of such tools that provides the flexibility to write test scripts in python and the web ui is also quite useful and the test reports can be easily exported to CSV or Html as well. So overall it’s quite a handy load testing tool, I hope you find this article worth your time and hope you add locust as load testing tool in your next project.</p><p>If you want to support me on my blogging journey feel free to check out my Ko-fi page :</p><figure><a href="https://ko-fi.com/srvzblogs"><img alt="" src="https://cdn-images-1.medium.com/max/286/1*od_ub_xWUuru1uyr4iqbJQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd42663e1b17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Stunning Graphs in the Terminal with Python]]></title>
            <link>https://medium.com/@SrvZ/how-to-create-stunning-graphs-in-the-terminal-with-python-2adf9d012131?source=rss-435b363fb359------2</link>
            <guid isPermaLink="false">https://medium.com/p/2adf9d012131</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[scripting]]></category>
            <dc:creator><![CDATA[Sourav De]]></dc:creator>
            <pubDate>Sun, 14 May 2023 12:31:38 GMT</pubDate>
            <atom:updated>2023-05-14T12:31:38.058Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NrHbf36fuQ83CL0A" /><figcaption>Photo by <a href="https://unsplash.com/@behy_studio?utm_source=medium&amp;utm_medium=referral">Behnam Norouzi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong><em>A picture is worth thousand words</em></strong></blockquote><p>In today’s data-driven world, visualizations or graphs do express a story worth a thousand words. Visualizations provide quick and effective communication media to convey data which if shared with text or table might be difficult to comprehend.</p><p>While there are many powerful visualization tools available, sometimes we need a quick and easy way to visualize data directly in the terminal. Whether we’re working remotely, on a server, or just need to share a quick visualization with a colleague, the ability to plot graphs in the terminal can be incredibly useful.</p><p>Let’s see a simple example scenario, I am trying to find out the latency of AWS regions from my location. I got the data and want to compare it now:</p><pre>data = [<br>    {<br>        &quot;#&quot;: 1,<br>        &quot;AWS Region Name&quot;: &quot;US East (N. Virginia)&quot;,<br>        &quot;Region Code&quot;: &quot;us-east-1&quot;,<br>        &quot;Mean&quot;: &quot;741 ms&quot;,<br>        &quot;Median&quot;: &quot;730 ms&quot;,<br>        &quot;Min&quot;: &quot;723 ms&quot;,<br>        &quot;Max&quot;: &quot;780 ms&quot;,<br>    },<br>    {<br>        &quot;#&quot;: 2,<br>        &quot;AWS Region Name&quot;: &quot;US East (Ohio)&quot;,<br>        &quot;Region Code&quot;: &quot;us-east-2&quot;,<br>        &quot;Mean&quot;: &quot;525 ms&quot;,<br>        &quot;Median&quot;: &quot;530 ms&quot;,<br>        &quot;Min&quot;: &quot;244 ms&quot;,<br>        &quot;Max&quot;: &quot;797 ms&quot;,<br>    },<br>    {<br>        &quot;#&quot;: 3,<br>        &quot;AWS Region Name&quot;: &quot;US West (N. California)&quot;,<br>        &quot;Region Code&quot;: &quot;us-west-1&quot;,<br>        &quot;Mean&quot;: &quot;540 ms&quot;,<br>        &quot;Median&quot;: &quot;535 ms&quot;,<br>        &quot;Min&quot;: &quot;270 ms&quot;,<br>        &quot;Max&quot;: &quot;819 ms&quot;,<br>    },<br>    {<br>        &quot;#&quot;: 4,<br>        &quot;AWS Region Name&quot;: &quot;US West (Oregon)&quot;,<br>        &quot;Region Code&quot;: &quot;us-west-2&quot;,<br>        &quot;Mean&quot;: &quot;602 ms&quot;,<br>        &quot;Median&quot;: &quot;594 ms&quot;,<br>        &quot;Min&quot;: &quot;299 ms&quot;,<br>        &quot;Max&quot;: &quot;923 ms&quot;,<br>    },<br>    {<br>        &quot;#&quot;: 5,<br>        &quot;AWS Region Name&quot;: &quot;Africa (Cape Town)&quot;,<br>        &quot;Region Code&quot;: &quot;af-south-1&quot;,<br>        &quot;Mean&quot;: &quot;632 ms&quot;,<br>        &quot;Median&quot;: &quot;627 ms&quot;,<br>        &quot;Min&quot;: &quot;320 ms&quot;,<br>        &quot;Max&quot;: &quot;953 ms&quot;,<br>    },<br>    {<br>        &quot;#&quot;: 6,<br>        &quot;AWS Region Name&quot;: &quot;Asia Pacific (Melbourne)&quot;,<br>        &quot;Region Code&quot;: &quot;ap-southeast-4&quot;,<br>        &quot;Mean&quot;: &quot;599 ms&quot;,<br>        &quot;Median&quot;: &quot;598 ms&quot;,<br>        &quot;Min&quot;: &quot;296 ms&quot;,<br>        &quot;Max&quot;: &quot;905 ms&quot;,<br>    },<br>    {<br>        &quot;#&quot;: 7,<br>        &quot;AWS Region Name&quot;: &quot;Asia Pacific (Hong Kong)&quot;,<br>        &quot;Region Code&quot;: &quot;ap-east-1&quot;,<br>        &quot;Mean&quot;: &quot;362 ms&quot;,<br>        &quot;Median&quot;: &quot;361 ms&quot;,<br>        &quot;Min&quot;: &quot;353 ms&quot;,<br>        &quot;Max&quot;: &quot;374 ms&quot;,<br>    },<br>]<br><br>print(&quot;\nAWS Ping Test results: &quot;)<br>print(&quot;=========================&quot;)<br>for d in data:<br>    print(d[&quot;Region Code&quot;], &quot;\t&quot;, d[&quot;Mean&quot;])<br><br><br>print(&quot;\nAWS Ping Test results: &quot;)<br>print(&quot;=========================&quot;)<br>for d in data:<br>    ms = int(d[&quot;Mean&quot;].replace(&quot; ms&quot;, &quot;&quot;))<br>    ms_bar = round(ms / 10)<br>    print(d[&quot;Region Code&quot;], &quot;\t&quot;, &quot;*&quot; * ms_bar)</pre><p>The output is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*68kGgFiqIVfqRQC1EHIRUw.png" /></figure><p>If we take a quick look although both the tables give us similar info but it’s easy to find the lowest latency in the bar graph. From this quick demonstration, we can actually see the usefulness of such CLI visualizations.</p><p>Now in some cases, a quick helper function to draw such graphs might be more useful and efficient than importing external modules. We will explore the external modules as well but let’s first do it ourselves!</p><pre>def draw_bar(value, legend=None, char=&quot;❚&quot;):<br>    if legend:<br>        print(legend, &quot;\t&quot;, char * value)<br>    else:<br>        print(char * value)<br><br>print(&quot;\nAWS Ping Test results: &quot;)<br>print(&quot;=========================&quot;)<br>for d in data:<br>    print(d[&quot;Region Code&quot;], &quot;\t&quot;, d[&quot;Mean&quot;])<br><br><br>print(&quot;\nAWS Ping Test results: &quot;)<br>print(&quot;=========================&quot;)<br>for d in data:<br>    ms = int(d[&quot;Mean&quot;].replace(&quot; ms&quot;, &quot;&quot;))<br>    ms_bar = round(ms / 10)<br>    # print(d[&quot;Region Code&quot;], &quot;\t&quot;, &quot;*&quot; * ms_bar)<br>    <br>    draw_bar(ms_bar, d[&quot;Region Code&quot;])<br>    draw_bar(ms_bar, d[&quot;Region Code&quot;], &quot;☐&quot;)<br>    draw_bar(ms_bar, d[&quot;Region Code&quot;], &quot;░&quot;)</pre><p>Here I have added a simple function to draw the bar graph and used some Unicode characters to make the graph a bit more interesting and aesthetically pleasing than our previous example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*3ZalSZjUsMrPIezaJu-o4A.png" /></figure><p>By providing your own Unicode character it can be easily changed as per your own choice or taste (mine are not very good! Proof is in the picture 😂)</p><p>Although a simple function might help in this case, however, if your script needs better visualizations there are some really good external modules let&#39;s explore these I have already used some of them in my projects.</p><h4><a href="https://github.com/kressi/terminalplot"><strong>1. Terminalplot</strong></a></h4><p>Terminalplot is one of the modules that are very useful for simple scatter plots. It’s very easy to use and only a few lines of code to add to your script.</p><pre>from terminalplot import plot<br><br>x = range(0, 100, 2)<br>y = [i**2 for i in x]<br>plot(x, y)</pre><p>This will result in the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ob16MDaxIuKUs2F-V6k76Q.png" /></figure><p>The very easy-to-use modules come at the cost of not being very flexible, the plot character is not customizable and will print “*”. Also, there is no option to show labels or plot legends. So if you need a quick solution to plot any kind of mathematical expression without very minute resolution then it’s good for that purpose</p><h4>2. <a href="https://pypi.org/project/asciichartpy/">Asciichartpy</a></h4><p>This is a Python-ported version of the NPM module with the name <a href="https://pypi.org/project/asciichartpy/">asciichart</a>. This one I have used this module in one of my projects <a href="https://github.com/Sr-vZ/pynetmon/tree/main">pynetmon</a> if you’re more interested you can read it <a href="https://medium.com/@SrvZ/en-rich-your-python-console-scripts-37926d8cd5bf">here </a>about how I used it in the project.</p><p>Coming back to the module although the documentation for Python is bit missing but it’s very similar to the NodeJS version so pretty easy to use let&#39;s see an example:</p><pre>import asciichartpy as acp<br>from random import randint<br><br>x = [randint(0, 10) for _ in range(100)]<br><br>print(acp.plot(x))</pre><p>This will result in the following chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*y2AuiP81Vu0yQl9PLmkUBw.png" /></figure><p>This is very useful where you need to plot streaming data and that’s why I used it in my pynetmon project to plot the ingress and egress data on the network interface. You can also provide some configurations to customize the units or text format shown and a few more options to explore or experiment with. If you’re building a Text-based User Interface it works great with such libraries like Rich or Textual.</p><h4>3. <a href="https://github.com/justnoise/termplot">Termplot</a></h4><p>Termplot is similar to Terminalplot mentioned above but with little more flexibility to customize different plot types.</p><pre>import math<br>from termplot import Plot<br>xvals, yvals = [], []<br>for i in range(0, 2000, 5):<br>    xx = i / 100.0<br>    xvals.append(xx)<br>    yvals.append(math.sin(xx) * float(i ** 0.5))<br>Plot(xvals, yvals, LINE)</pre><p>This will result in the following scatter plot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*vea-AFtIw9A0Tp4aq5Y7Gg.png" /><figcaption>Source: <a href="https://github.com/justnoise/termplot">https://github.com/justnoise/termplot</a></figcaption></figure><h4>4. <a href="https://github.com/sgeisler/termgraph">Termgraph</a></h4><p>If you need to plot a candlestick plot for any kind of financial dashboard in the terminal in that case this this module is helpful. It only does one type of plot but it’s good using Unicode character set to plot a candlestick chart is really impressive. It’s not pip installable and there’s a pip module with the same name so be careful of the ambiguity, right now you can only use it by cloning the source to your project.</p><p>Here is an example Termgraph rendering OHLC chart from CSV data on Windows Terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*000Qa6Rr0Jz4WTEUl8hVwA.gif" /><figcaption>Termgraph OHLC on Terminal!</figcaption></figure><h4>5. <a href="https://github.com/tammoippen/plotille">Plotille</a></h4><p>Plotile uses a really cool approach using Braille dots to print some really good resolution charts. This is one of the relatively new modules compared to the others mentioned above. I am actually considering swapping Plotile with asciicharts for pynetmon graphs.</p><p>It’s very easy to use and integrate into any script, let’s check an example:</p><pre>import plotille<br>import psutil<br><br>temps = []<br>n = []<br>for i in range(100):<br>    n.append(i)<br>    temps.append(psutil.cpu_percent(interval=0.1))<br><br>fig = plotille.Figure()<br>print(plotille.plot(n, temps, height=30, width=60, interp=&quot;linear&quot;, lc=&quot;cyan&quot;))</pre><p>In the example I am storing the CPU usage of my system every 0.1 seconds into a list this is for simplicity in the actual application we’ll probably do it in real-time but let’s check the results for now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*r0XzbxPEVRf7U_qIhA9KUg.png" /></figure><p>As you can see the graph resolution is more precise and aesthetically better also the module is easily customizable so you can change the line color, background, etc without much hassle.</p><p>In the example I have only used a simple plot, there are also scatter or histogram plots available. Also if you need a custom graph that can be done by manipulating the Canvas. Even images can be rendered in Canvas like the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*oi-QZoaR2Eem12PpTH71mg.png" /><figcaption>Source: <a href="https://github.com/tammoippen/plotille/tree/master">Plotile example</a></figcaption></figure><p>Pretty cool isn’t it and also enables a lot of possibilities if you’re interested in ASCII arts.</p><h4>6. Termcharts</h4><p>The common pattern of the libraries discussed so far is mostly limited to line, bar, and scatter plots mostly. However, if you need to plot a nice pie chart or donut chart, (yes those circular thingies from usually the business presentations on a long and boring meeting that could’ve easily conveyed in an email, but hey how’s that fun let’s invite everyone and waste 30 mins of time and achieve nothing in the end🤣sorry for the rant, but you got the gist.)</p><p>Now TLDR; Termcharts lets you print pie and donut charts in the terminal and with cool color combinations by default.</p><p>For our example let’s plot my awesome schedule throughout the day:</p><pre>import termcharts<br>from rich import print<br>from rich.layout import Layout<br>from rich.panel import Panel<br><br>data = {&quot;Work&quot;: 8, &quot;Sleep&quot;: 6, &quot;Gaming&quot;: 4, &quot;Netflix&quot;: 4, &quot;Misc&quot;: 2}<br><br>chart1 = termcharts.bar(data, title=&quot;Time of my life&quot;, rich=True)<br>chart2 = termcharts.bar(data, title=&quot;Time of my life&quot;, mode=&quot;v&quot;, rich=True)  # vertical<br><br>chart_pie = termcharts.pie(data, title=&quot;Time of my life&quot;, rich=True)<br><br>chart_donut = termcharts.doughnut(data, title=&quot;Time of my life&quot;, rich=True)<br><br>layout = Layout()<br>layout.split_column(Layout(name=&quot;upper&quot;), Layout(name=&quot;lower&quot;))<br>layout[&quot;upper&quot;].split_row(<br>    Layout(name=&quot;uleft&quot;),<br>    Layout(name=&quot;uright&quot;),<br>)<br>layout[&quot;lower&quot;].split_row(<br>    Layout(name=&quot;lleft&quot;),<br>    Layout(name=&quot;lright&quot;),<br>)<br>layout[&quot;uleft&quot;].update(Panel(chart1))<br>layout[&quot;uright&quot;].update(Panel(chart2))<br>layout[&quot;lleft&quot;].update(Panel(chart_pie))<br>layout[&quot;lright&quot;].update(Panel(chart_donut))<br><br>print(layout)</pre><p>This will result in the following (disclaimer I am nowhere near this level of productivity or scheduling 😆this is for demonstration purposes only, also the death star is not part of the charts just my terminal background.):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRvDUcrULLh2uUsUjLYlbA.png" /></figure><p>This module can be a nice addition to any kind of dashboard that needs this type of chart to render on the terminal if needed.</p><h4>7. <a href="https://github.com/piccolomo/plotext">Plotext</a></h4><p>Plotext is probably the most versatile of the modules we discussed in this article so far (and I saved it for the last, such a coincidence! 💡). Plotext supports most types of charts which are scatter, line, bar, histogram, datetime (time-series), candlestick some special type charts such as error plots, confusion matrices, event timelines, etc. It can show images and gifs not only that it can even play videos on the terminal but too from youtube directly!</p><p>It’s time for some examples let’s try the candlestick chart first, we have done one before with termgraph but personally I think plotext resolution is a bit better.</p><pre>import plotext as plt<br>import yfinance as yf<br><br>plt.date_form(&quot;d/m/Y&quot;)<br>start = plt.string_to_datetime(&quot;01/01/2023&quot;)<br>end = plt.today_datetime()<br>data = yf.download(&quot;SPY&quot;, start, end)<br>dates = plt.datetimes_to_string(data.index)<br><br>plt.clf()<br>plt.theme(&quot;dark&quot;)<br>plt.candlestick(dates, data)<br>plt.title(&quot;SPY Stock Price CandleSticks&quot;)<br><br>plt.show()</pre><p>I have changed the theme to dark mode so that fellow dark-side embracers don’t burn their eyes! The default theme is white similar to the ones we used to see with matplotlib charts. The candlestick chart looks like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eWbqLcT2V-2f4_Mb3UK8jQ.png" /><figcaption>Plotext Candlesticks chart</figcaption></figure><p>For the video Demo, I will use everyone’s all-time favorite video which you will see shortly!</p><pre>import plotext as plt<br><br>src = &quot;./Rick_Astley_Never_Gonna_Give_You_Up.mp4&quot;<br>plt.play_video(src, from_youtube=True)</pre><p>Plotext mentions it can directly play videos from Youtube however when I tried I couldn’t play it and a lot of dependencies issues popped up so I used a local video file.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGnXzwFgntBY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGnXzwFgntBY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGnXzwFgntBY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9706ebb1c3ed9d255306e37404b5e41b/href">https://medium.com/media/9706ebb1c3ed9d255306e37404b5e41b/href</a></iframe><p>So now we can enjoy Rick Ashley in the Terminal as well! The from_youtube=True is needed for the audio to play if removed or set to False only the video will play without the audio.</p><p>That’s it folks I have shared 7 cool modules that you can integrate into your next terminal scripts or projects to make them look stunning!</p><p>If you enjoyed this article and want to support or encourage me feel free to follow me or subscribe to my newsletter or follow me on <a href="https://twitter.com/SrvzBlogs">Twitter</a>.</p><p>Also if you want to support my future blogging endeavor, you can buy me a coffee!</p><figure><a href="https://ko-fi.com/srvzblogs"><img alt="" src="https://cdn-images-1.medium.com/max/286/0*3i1j8eYmL2_JmZoC.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2adf9d012131" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a CLI Music Player with Python]]></title>
            <link>https://python.plainenglish.io/how-to-build-a-cli-music-player-with-python-91f6b313e860?source=rss-435b363fb359------2</link>
            <guid isPermaLink="false">https://medium.com/p/91f6b313e860</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[music-player]]></category>
            <category><![CDATA[rich-ui]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mp3]]></category>
            <dc:creator><![CDATA[Sourav De]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 12:13:26 GMT</pubDate>
            <atom:updated>2023-02-05T12:13:26.616Z</atom:updated>
            <content:encoded><![CDATA[<p>Build an awesome-looking Music Player with cool animations and more to relive the retro era.</p><figure><img alt="PyAudioPlayer" src="https://cdn-images-1.medium.com/max/1024/1*bEtNUM4Q_6SXxzpvSieuTA.jpeg" /></figure><p>I grew up listening to music in Winamp or Windows Media Player back in the Windows XP era. In recent times enjoying our music has been replaced by popular streaming services such as Spotify, Youtube Music, and SoundCloud to name a few however for me Music players always gave me that nostalgic retro feeling of enjoying music.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*MqZPK2-Q0uOAk_8cJhQcEw.png" /></figure><p>I actually did build an <a href="https://medium.com/@SrvZ/build-a-audio-player-in-electron-e1b133776c6">audio player in Electron</a> JS a long time ago in JavaScript utilizing the WebAudioAPI however that was a long time ago and I wanted to try something new this time.</p><p>Recently I was working on a project using the python Rich library for <a href="https://github.com/Sr-vZ/pynetmon">Pynetmon</a>, so I thought maybe use the same library to build a music player within the Command Line Interface (CLI) with some nice looking UI elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xk4AaOB_tnatSro-M8KpZg.gif" /><figcaption>Python Audio player in action</figcaption></figure><p>To start our project I found out there are multiple libraries out there that let you play music or more specifically mp3 files, for example, playsound, pydub, etc. however they have certain dependencies or are not uniform across different Operating Systems (OS). I needed a library that can play mp3 files in Windows and Linux without any other dependencies which luckily Pygame mixer fulfills my requirement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*PhIVdNijUt14rs6j4oCiyQ.png" /></figure><p>Pygame mixer supports a wide variety of methods to play, pause, rewind, and queue music files without much hassle so it’s pretty easy to ease.</p><p>If we want to play a sample mp3 file we can do this by following</p><pre>from pygame import mixer<br><br>music_file = &quot;./sample.mp3&quot;<br>mixer.music.load(music_file)<br>mixer.music.play()</pre><p>For a full-fledged Music player, we need more components such as the currently playing song name, seek bar to show how long it has been played and the remaining portion in minutes, and a queue or list of songs if loading from a folder. More aesthetics can be added such as a Spectrogram or any kind of animation but those are for purely better presentation rather than a functionality point of view.</p><p>First, we will need to install rich module to work on the UI to do that use the following command in the terminal:</p><pre>pip install rich</pre><p>If you are cloning from the git repo follow the readme instructions or do the following:</p><pre>pip install -r requirements.txt</pre><p>For the basic layout, we can use the following for reference and then create or segment the main screen into different parts to show different information and update at certain intervals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bIHzSMi_cu6Jj8E_bnPBmA.jpeg" /></figure><p>In rich we have a Layout to create or segment the main screen into parts we can do it by the following code:</p><pre>from rich.layout import Layout<br><br><br>def draw_ui(layout):<br><br>    layout.split(<br>        Layout(name=&quot;header&quot;, size=3),<br>        Layout(<br>            name=&quot;main&quot;,<br>            size=25,<br>        ),<br>        Layout(name=&quot;footer&quot;, size=3),<br>    )<br>    # header to show app name on top<br>    layout[&quot;header&quot;].update(<br>        Panel(<br>            Align.center(&quot;[bold][#feff6e] ♪ Python CLI Audio Player[/#feff6e][/bold]&quot;),<br>            border_style=default_theme[&quot;panel_border&quot;],<br>        )<br>    )<br><br>    layout[&quot;main&quot;].split_row(Layout(name=&quot;disk&quot;), Layout(name=&quot;player&quot;, ratio=3))<br>    <br>    # previsouly the disk ascii art wasn&#39;t fitting so had to set min size<br>    # layout[&quot;disk&quot;].minimum_size = 20<br>    layout[&quot;disk&quot;].update(<br>        Panel(<br>            Align.center(&quot;\n&quot;.join(disk_frames[&quot;frame1&quot;]), vertical=&quot;middle&quot;),<br>            border_style=default_theme[&quot;panel_border&quot;],<br>        )<br>    )<br>    <br>    layout[&quot;player&quot;].split_column(<br>        Layout(name=&quot;now_playing&quot;, size=3),<br>        Layout(name=&quot;media_n_spectro&quot;, size=22),<br>    )<br>    <br>    layout[&quot;media_n_spectro&quot;].split_row(<br>        Layout(name=&quot;media_controls&quot;), Layout(name=&quot;spectro&quot;)<br>    )<br>    layout[&quot;media_controls&quot;].split_column(<br>        Layout(name=&quot;song_list&quot;, size=10), Layout(name=&quot;media_buttons&quot;)<br>    )<br><br>    layout[&quot;media_buttons&quot;].split_column(<br>        Layout(name=&quot;media_big_buttons&quot;), Layout(name=&quot;media_user_controls&quot;, size=3)<br>    )<br><br>    layout[&quot;media_user_controls&quot;].update(<br>        Panel(<br>            Align.center(<br>                &quot;[bold][#feff6e]Pre(v) (P)lay/Pause (S)top (N)ext  (R)epeat  (Q)uit (+)Vol (-)Vol [/#feff6e][/bold]&quot;<br>            ),<br>            title=&quot;Controls&quot;,<br>            border_style=default_theme[&quot;panel_border&quot;],<br>        )<br>    )<br>    layout[&quot;footer&quot;].update(<br>        Panel(<br>            Align.center(<br>                &quot;[bold][#feff6e] Created with [#ff2b2b]♥[/#ff2b2b] by [link=https://github.com/Sr-vZ]SrvZ[/link] [/#feff6e][/bold]&quot;<br>            ),<br>            border_style=default_theme[&quot;panel_border&quot;],<br>        )<br>    )<br>    return layout</pre><p>This function we will need to call this once in our main function and then from the returned layout we will be updating this using a rich live display. Before that, we will need to create the song list we can use a table to create that it’ll be great if the currently playing song is highlighted so let’s see how we can do that:</p><pre>default_config = {&quot;music_file_location&quot;: &quot;./sample-music&quot;, &quot;default_vol&quot;: 0.5}<br><br># loading mp3 files from default file location<br>for file in os.listdir(default_config[&quot;music_file_location&quot;]):<br>    if file.endswith(&quot;.mp3&quot;):<br>        music_list.append(os.path.join(default_config[&quot;music_file_location&quot;], file))<br><br>def generate_songlist(layout, song_list):<br>    global currently_playing<br>    currently_playing_name = currently_playing.split(&quot;\\&quot;)[-1].replace(&quot;.mp3&quot;, &quot;&quot;)<br>    table = Table(<br>        show_lines=False,<br>        box=box.SIMPLE,<br>        border_style=default_theme[&quot;panel_border&quot;],<br>    )<br>    table.add_column(&quot;File&quot;, justify=&quot;left&quot;, style=&quot;cyan&quot;, no_wrap=False)<br>    table.add_column(&quot;Duration&quot;, justify=&quot;right&quot;, style=&quot;green&quot;)<br><br>    for song in song_list:<br>        song_meta = MP3(song)<br>        dur = time_format(song_meta.info.length)<br>        name = song.split(&quot;\\&quot;)[-1].replace(&quot;.mp3&quot;, &quot;&quot;)<br>        if name == currently_playing_name:<br>            # highlights the entire row <br>            table.add_row(name, dur, style=&quot;red on white&quot;)<br>        else:<br>            table.add_row(name, dur)<br><br>    return Panel(<br>        table,<br>        border_style=default_theme[&quot;panel_border&quot;],<br>        title=&quot;[#feff6e]Music Queue&quot;,<br>    )</pre><p>We will need to call this function from the live display section to reflect the changes on UI.</p><p>I wanted to add a little bit of animation to make the player a bit more attractive but in Terminal it’s very limited as we can’t display images or gifs. However, we can show ASCII art was very popular before and was often used very widely in forums or orkut (not sure if anyone remembers or has ever heard of it now). I used a gif of a rotating vinyl disk and separated the frames and converted the frames into ASCII art. Here is a sample frame:</p><pre>&quot;frame1&quot;: [<br>            &quot;⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⢀⣀⣀⣀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⢀⣠⣴⢶⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣶⣦⣤⣀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⣠⡴⠞⠋⠁⡀⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣄⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⡀⡀⡀⡀⡀⡀⢀⣴⠞⠁⡀⡀⡀⢀⣀⠤⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⡀⡀⡀⡀⡀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⡀⡀⡀⡀⡀⣴⠟⠁⡀⡀⡀⡠⠖⠉⡀⠄⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⡀⡀⡀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⡀⡀⡀⢠⠞⠁⡀⡀⢀⡴⠋⡀⡀⡀⡀⡀⣄⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⡀⡀⡀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⡀⡀⣰⠏⡀⡀⡀⣠⠊⡀⡀⡀⡀⢀⡴⠞⠿⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⡀⡀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⡀⢠⠏⡀⡀⡀⡼⠁⡀⡀⡀⢀⡴⠋⢀⡀⢚⣽⣿⣿⡿⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⢀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⢀⣿⣄⣄⡀⣼⠁⡀⡀⢠⣠⡟⡀⡀⢫⣶⠟⠉⡀⡀⡀⡀⡀⡀⠈⠙⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⣿⡄⡀⡀&quot;,<br>            &quot;⡀⡀⢸⣿⣿⣿⣿⣿⣾⣶⣦⣴⣏⣻⣾⣴⡟⠁⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⠘⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⣰⣿⣧⡀⡀&quot;,<br>            &quot;⡀⡀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⠈⣿⣿⣿⣿⣿⣿⣿⣿⡿⠁⣼⣿⣿⣿⡀⡀&quot;,<br>            &quot;⡀⡀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⣿⣿⣿⣿⣿⣿⣿⡟⢁⣾⣿⣿⣿⣿⡀⡀&quot;,<br>            &quot;⡀⡀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⣿⣿⣿⣿⣿⣿⠟⢀⣾⣿⣿⣿⣿⣿⡀⡀&quot;,<br>            &quot;⡀⡀⢹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡄⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⣰⣿⢿⣿⠿⠋⡀⡀⢿⣿⣿⣿⣿⣿⡿⡀⡀&quot;,<br>            &quot;⡀⡀⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⣠⣾⡿⠁⠉⠙⡀⡀⡀⡀⠉⠙⠛⠻⠿⢿⠇⡀⡀&quot;,<br>            &quot;⡀⡀⡀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣤⣄⣀⣀⣀⣤⣴⣾⠟⠉⠛⠁⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⡀⡀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⣏⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡐⡀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⡀⡀⡀⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡩⡐⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⡀⡀⡀⡀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠈⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⡀⡀⡀⡀⡀⡀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⡀⡀⡀⡀⡀⡀⡀⢀⠔⠁⡀⡀⡀⡀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⠙⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⡀⡀⡀⡀⢀⠠⠂⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⠉⠛⠿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣀⠠⠔⠊⠁⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀&quot;,<br>            &quot;⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⠈⠉⠙⠛⠛⠛⠛⠛⠛⠛⠛⠉⠁⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀&quot;<br>        ]</pre><p>Similarly, for buttons I initially thought of using Unicode media control icons but those looked very small so used some images of media buttons and converted them to their equivalent ASCII art as well</p><p>For user control I used keyboard module in python and created hotkeys for certain keys so that users can interact with the player by pressing the mapped keys to the desired functions. I wrote the individual functions for each control and finally attached them to a hotkey in the user_controls function and called user_controls in the main.</p><pre>def exit_player():<br>    player.music.stop()<br>    os._exit(0)<br><br><br>def play_n_pause():<br>    global player_state<br>    if player.music.get_busy():<br>        player.music.pause()<br>        player_state = None<br>    else:<br>        player.music.unpause()<br>        player_state = &quot;playing&quot;<br><br><br>def next_track():<br>    global song_idx, currently_playing<br>    song_idx = music_list.index(currently_playing)<br>    if song_idx == len(music_list):<br>        song_idx = 0<br>    elif song_idx &lt; len(music_list):<br>        song_idx = song_idx + 1<br>    if len(music_list) &gt; 0:<br>        currently_playing = music_list[song_idx]<br>    # currently_playing = music_list[song_idx]<br>    player.music.load(currently_playing)<br>    player.music.play()<br><br><br>def prev_track():<br>    global song_idx, currently_playing<br>    song_idx = music_list.index(currently_playing)<br>    if song_idx == 0:<br>        song_idx = len(music_list)<br>    elif song_idx &gt; 0:<br>        song_idx = song_idx - 1<br>    if len(music_list) &gt; 0:<br>        currently_playing = music_list[song_idx]<br>    player.music.load(currently_playing)<br>    player.music.play()<br><br><br>def increase_vol():<br>    curr_vol = player.music.get_volume()<br>    if curr_vol &gt; 1:<br>        curr_vol = 1<br>    else:<br>        curr_vol = curr_vol + 0.1<br>    player.music.set_volume(curr_vol)<br><br><br>def decrease_vol():<br>    curr_vol = player.music.get_volume()<br>    if curr_vol &lt; 0:<br>        curr_vol = 0<br>    else:<br>        curr_vol = curr_vol - 0.1<br>    player.music.set_volume(curr_vol)<br><br><br>def user_controls():<br>    kb.add_hotkey(&quot;p&quot;, play_n_pause)<br><br>    kb.add_hotkey(&quot;r&quot;, lambda: player.music.rewind())<br><br>    kb.add_hotkey(&quot;s&quot;, lambda: player.music.stop())<br><br>    kb.add_hotkey(&quot;v&quot;, prev_track)<br><br>    kb.add_hotkey(&quot;n&quot;, next_track)<br><br>    kb.add_hotkey(&quot;+&quot;, increase_vol)<br><br>    kb.add_hotkey(&quot;-&quot;, decrease_vol)<br><br>    kb.add_hotkey(&quot;q&quot;, exit_player)</pre><p>Here’s a demo of the Music player in action:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FS8XlMwBFnq4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DS8XlMwBFnq4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FS8XlMwBFnq4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a8df92b9492a48307892d3e8a7f7560/href">https://medium.com/media/5a8df92b9492a48307892d3e8a7f7560/href</a></iframe><p>If you liked this project and want to try it yourself you can fork the repo <a href="https://github.com/Sr-vZ/PyAudioPlayer">here</a>. I hope you have found this useful. Thank you for reading.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em>, and</em></strong><em> </em><a href="https://discord.com/invite/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Build awareness and adoption for your tech startup with </em></strong><a href="https://circuit.ooo/?utm=publication-post-cta"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91f6b313e860" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/how-to-build-a-cli-music-player-with-python-91f6b313e860">How to build a CLI Music Player with Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to en”Rich” your Python console scripts]]></title>
            <link>https://medium.com/@SrvZ/en-rich-your-python-console-scripts-37926d8cd5bf?source=rss-435b363fb359------2</link>
            <guid isPermaLink="false">https://medium.com/p/37926d8cd5bf</guid>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[rich]]></category>
            <category><![CDATA[network]]></category>
            <dc:creator><![CDATA[Sourav De]]></dc:creator>
            <pubDate>Sat, 14 Jan 2023 16:56:33 GMT</pubDate>
            <atom:updated>2023-01-24T08:40:14.364Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create awesome command line interfaces in Python</h3><figure><img alt="pynetmon in action" src="https://cdn-images-1.medium.com/max/1024/1*9AwFDqe9jlmm2GOvupzypw.png" /></figure><p>Recently I wrote a post on <a href="https://medium.com/@SrvZ/how-to-make-your-python-gui-look-awesome-9372c42d7df4">Python GUI using ttkbootstrap</a>, a GUI definitely provides better UX(User Experience) and makes our application/script easy to use. However, a lot of times we don’t need a GUI in the first place for example, in Dev and Production environments most Linux servers we use don’t have a DE (Desktop Environment) installed so we just ssh to the server and start running our scripts.</p><p>In such scenarios, we actually don’t need a GUI however we do need to monitor the output of our scripts so some level of visual feedback is still required. Now looking at a long-running stream of log messages or errors can be a daunting and boring task</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*opCVhvwxLWhEhamjBrcmbA.gif" /></figure><p>So how about we make our gloomy wall of text a fresh look 😎. Textualize released a new Python module <a href="https://rich.readthedocs.io/en/latest/">Rich</a> which helps us create some great-looking Command Line Interfaces which previously would require a lot of effort and thus en”rich”ing our console experience 😀. Here is the demo image showing all the features supported by rich:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYAdAQP_i5h7xE_eWcvreQ.png" /></figure><p>You can test the same on your system as well, to do that you’ll need to install the module first which you can do by the following command on the terminal/console:</p><pre>python -m pip install rich</pre><p>If you have both Python2 and 3 installed maybe you’ll need to change to python3 or better use venv before installing. To view the demo interface on your terminal:</p><pre>python -m rich</pre><p>That’ll give you a nice-looking interface check for color compatibility some terminal emulators might not support it out of the box and you might need to change the color mode to Truecolor or 16bit mode. I use Windows Terminal which supports it perfectly without any issues.</p><p>Well, the rich module definitely looks pretty but what should we do with it. So let’s create something useful utilizing this library.</p><p>I recently had issues with my ISP and wasn’t getting the bandwidth I was promised. As the issue was very sporadic it was very difficult to monitor so I did what every Network engineer does in this situation and ran the ping command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6uqC5OthbHFGIKhU93la0A.gif" /></figure><p>Well, it’ll tell you if there is a drop or no connectivity etc. However I wanted to see some graphs and real-time up/downstream speeds so how about creating a Python script to just monitor those.</p><p>To show our system’s upload/download speed we need to monitor our ethernet or Wifi adapter. In Python, we have a very good module to monitor system parameters which is psutil. So I will import that module first and then write a function to monitor the active network interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gQ1PvQp8-cJScN4Z" /></figure><p>The net_usage function calls the net_io_counters() function to get the active network interface details. To measure the speed we will need to compare the within a timeframe which is 1 second here so we measure the initial sent and received bytes then wait for a second and then measure again and finally compare the both to get the actual speed. When executed it&#39;ll give the following results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/0*mWrsh_e1Qw39aQSj" /></figure><p>Next, we will use this function and create our interface rich for graphs I found an excellent module <a href="https://pypi.org/project/asciichartpy/">asciichartpy</a> it&#39;s an npm module ported to python. it&#39;ll help us generate graphs like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*a9NTP00pAPJ-J2DZ" /></figure><p>For the layout I will use the following template:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5XdQzN-hbTsVydcc" /></figure><p>I think it’s a pretty basic and neat way to show all the relevant information we need to show. This is achieved by using the layout in rich and for the graphs, I will use the Live Display, with layout we can split our CLI into segments and control or update each segment on what information we want to present on the screen. Live display helps auto-refresh the screen at certain intervals and is very useful here for the graphs to update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*VSazAngVzdcHSd9U" /></figure><p>So here the layout is split into “header”, “main” and “footer”. The “header” just contains the name of the script “Python Network Monitoring” the footer contains control options right now only one button to exit the script.</p><p>The “main” is split into “info” and “graphs” vertically and “graphs” includes two separate sections for up and downstream graphs each. The info shows a real-time up and down speed and all the open ports in use at the moment.</p><p>So we finally get a UI that looks like the following:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7kRW-dHkq5E%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7kRW-dHkq5E&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7kRW-dHkq5E%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/65ee2fb4a4e851d95e1f8db6bc5d970f/href">https://medium.com/media/65ee2fb4a4e851d95e1f8db6bc5d970f/href</a></iframe><p>The code is available on my <a href="https://github.com/Sr-vZ/pynetmon">GitHub</a> to feel free to contribute or modify it any way to would like to and make it more useful to your exact requirements.</p><p>If you find this article useful feel free to subscribe or follow me. Also if you want to support my blogging endeavor you can buy me a coffee!</p><figure><a href="https://ko-fi.com/T6T7HG1IK"><img alt="" src="https://cdn-images-1.medium.com/max/286/1*od_ub_xWUuru1uyr4iqbJQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37926d8cd5bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to make your Python GUI look awesome]]></title>
            <link>https://medium.com/@SrvZ/how-to-make-your-python-gui-look-awesome-9372c42d7df4?source=rss-435b363fb359------2</link>
            <guid isPermaLink="false">https://medium.com/p/9372c42d7df4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bootstrap]]></category>
            <category><![CDATA[gui]]></category>
            <category><![CDATA[tkinter]]></category>
            <dc:creator><![CDATA[Sourav De]]></dc:creator>
            <pubDate>Sat, 07 Jan 2023 14:54:09 GMT</pubDate>
            <atom:updated>2023-01-07T14:54:09.711Z</atom:updated>
            <content:encoded><![CDATA[<h3>A complete makeover for your boring Tkinter UI 😎</h3><p>The majority of the scripts I write usually run on CLI (Command Line Interface), however at a certain point it’s good to have a nice-looking GUI (Graphical User Interface) for simple applications. In my case my Network engineer colleagues who are not very familiar with Python or have started learning always prefer to have a simple GUI for our automation scripts.</p><p>It’s not difficult to build GUI in Python as we have Tkinter built-in module to create simple and functional GUI in minutes. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gMCYaFxTY9GtprMG" /></figure><p>if we execute this code we will be able to see the following window with a counter increasing on click.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*E8wkfiIlIqbSM-MlyuW3jQ.gif" /></figure><p>Now it does the job but we can definitely improve the UI to offer a better UX. Python does have a lot of options for UI development for example:</p><ul><li><a href="https://www.riverbankcomputing.com/software/pyqt/">PyQT5</a></li><li><a href="https://kivy.org/">Kivy</a></li><li><a href="https://github.com/python-eel/Eel">Eel</a></li><li><a href="https://pywebview.flowrl.com/examples/js_api.html">Pywebview</a></li></ul><p>PyQT5 and Kivy can produce great UI results but will definitely take a bit of effort and has a little bit of a learning curve. Eel and Pywebview take a different approach and leverages HTML, CSS, and JavaScript to render the UI elements and interaction this might be beneficial for programmers with good front-end experience to create a UI which is probably not possible with PyQT or Kivy.</p><p>Here is a sample todo app from Pywebview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8PVnyIuAUrgEdyEW.png" /></figure><p>That definitely looks nice! However, I will be honest I am not good with CSS 😅 I can’t center a div without looking up in StackOverflow 🤣. For any quick web development projects usually when we need a dashboard for monitoring stuff or for reporting purposes my first go-to is the Bootstrap framework. It’s easy to slap into any project and elements are pretty easy and simple enough for anyone to pick up and use almost instantaneously.</p><p>So why not apply the same here, use Bootstrap and create a UI and render the same with Pywebview. Well, that’s definitely a viable option but you’ll need interaction with the UI elements and backend for example in our previous code a counter increment happens on button click if we use Pywebview we will need to capture the UI interaction with JavaScript and then pass it on to a python function to handle the rest.</p><p>For a small project or rapid prototyping, this becomes a hassle in my personal opinion. What if we can use Bootstrap without actually using the review 😲.</p><p>That is achievable now with a new module <a href="https://ttkbootstrap.readthedocs.io/en/latest/">ttkbootstrap</a>. It leverages the Tkinter module with Bootstrap framework elements and gives a complete makeover to the GUI we were used to seeing with Tkinter.</p><p>Let’s re-create our previous counter with ttkbootstrap:</p><p>To install ttkbootstrap use the following command on the terminal or cmd prompt:</p><pre>python -m pip install ttkbootstrap</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FLaU8AzsENuxcOYY" /></figure><p>As we can there is not much deviation from our previous code but the results are different:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4aEMBfJV2xfLlmJLFmq_UQ.gif" /></figure><p>The rendered Button is a Boostrap styled Button without using any kind of web view, custom HTML, or CSS. The rendered window is directly from the python script just like our previous Tkinter example.</p><p>So what can we achieve with this ttkbootstrap module there is an example from the module website itself:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/0*QPqkyj-wfELkk577.png" /></figure><p>Pretty cool 😎 isn’t it? I am working on a few projects and planning to use this module, If you find this article useful please follow to get updates on similar projects.</p><p>Thanks for reading if you want to support me feel free to buy me a coffee!</p><figure><a href="https://ko-fi.com/srvzblogs"><img alt="" src="https://cdn-images-1.medium.com/max/286/1*od_ub_xWUuru1uyr4iqbJQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9372c42d7df4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to configure Docker proxy properly]]></title>
            <link>https://medium.com/@SrvZ/docker-proxy-and-my-struggles-a4fd6de21861?source=rss-435b363fb359------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4fd6de21861</guid>
            <category><![CDATA[corporate-proxy]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[proxy-server]]></category>
            <category><![CDATA[docker-proxy]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Sourav De]]></dc:creator>
            <pubDate>Sun, 25 Dec 2022 15:31:26 GMT</pubDate>
            <atom:updated>2023-01-17T19:27:21.450Z</atom:updated>
            <content:encoded><![CDATA[<p>My Struggles with Docker proxy and how did I overcome it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AD8RmUajldSHXYO7pqsEJg.png" /></figure><p>I recently joined a new organization and after getting around to spending a few days setting up my dev environment I sat down to do some actual work. My supervisor asked me to work on a project which requires Couchbase and I haven’t used it before. So I started procrastinating like a pro and fiddling around with what to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*lc8X3O42zZXwejzdm1U-EQ.gif" /></figure><p>After wasting some valuable time I finally started reading the official documentation which needs Couchbase docker to run the server and here is where I got stuck. Docker was unable to pull the Couchbase image from the docker registry.</p><p>After scratching my head a bit I figured that the server I was working on is behind the notorious Corpo proxy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*dH51v6iYvbJArtZq" /></figure><p>After figuring this out I reached out to my supervisor and asked for the proxies so that I can connect to the registry and after him handing that information over it was time to get to work again.</p><p>So the first thing I did was to check if there is a “docker.service.d” directory created in the path “/etc/systemd/system/” this server was Ubuntu 22.04 next I needed to create a “http-proxy.conf” file to save the proxies I got from my supervisor.</p><pre>mkdir -p /etc/systemd/system/docker.service.d<br>vi /etc/systemd/system/docker.service.d/http-proxy.conf</pre><p>In some cases you might need sudo so follow these instead:</p><pre>sudo mkdir -p /etc/systemd/system/docker.service.d<br>sudo vi /etc/systemd/system/docker.service.d/http-proxy.conf </pre><p>After the “http-proxy.conf” is created in the vi editor add the following lines to set up the proxy and work with the docker</p><pre>[Service] <br>Environment=&quot;HTTP_PROXY=http://X.X.X.X:80&quot; <br>Environment=&quot;HTTPS_PROXY=http://X.X.X.X:443&quot;</pre><p>Replace the X octets as per your proxy ip address.</p><p>Next to make the docker use this configuration we just added we will need to restart the docker daemon to reflect the changes. Follow the commands to restart the docker daemon:</p><pre>sudo systemctl daemon-reload <br>sudo systemctl restart docker <br>sudo systemctl show --property=Environment docker<br>Environment=HTTP_PROXY=http://X.X.X.X:80 HTTPS_PROXY=http://X.X.X.X:443</pre><p>“sudo systemctl show — property=Environment docker” shows the proxies we just configured it’s a way to check if you did it correctly or messed up anywhere 😵.</p><p>After I did this was able to pull the Couchbase image without any issues. So there’s our happy ending!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*5pMZ3F8R-XABPAyv" /></figure><p>If you find this article helpful, please clap or follow this will encourage me to write on similar topics more 😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4fd6de21861" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build an audio player in electron]]></title>
            <link>https://medium.com/@SrvZ/build-a-audio-player-in-electron-e1b133776c6?source=rss-435b363fb359------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1b133776c6</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[mp3]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[electron]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sourav De]]></dc:creator>
            <pubDate>Sat, 24 Jun 2017 15:30:16 GMT</pubDate>
            <atom:updated>2022-12-23T12:54:10.315Z</atom:updated>
            <content:encoded><![CDATA[<p>I stumbled upon the buzz around NodeJS and cool projects and libraries being discussed by developers around the globe.</p><p>So, as a newbie developer, I was curious to learn and try out the JavaScript-based server-side platform. I don’t have a web app in mind however I wanted to build a desktop program.</p><p>So the idea of an audio player came to my mind, yes I know there are at least hundreds of audio player out there which does the job far better than mine, however, that’s not my objective in the first place I just want to learn a new platform and build something useful, maybe optimize the performance later on.</p><p>So, the basic idea was to build something which will have play/pause, forward and backward buttons. An album art would have been cool however I had no idea how to read the ID3 tags from an mp3 file in JavaScript. Next, a playlist would be a cool feature too, and that’s it if I could make this much possible it would have been great.</p><p>As this was a desktop application in JavaScript so NW.js or Electron were my two choices, I went with electron as people are discussing how cool the library is, so I went with the flow.</p><p>I wanted an audio visualizer in my player as my initial computer music experience was in Winamp and really liked the software. So I wanted something similar to that.</p><p>The Web Audio API has the AudioAnalyser node which is required for the visualizer as it provides the frequency or time domain response in an array of provided fft size. For my app, I choose 128 as a bigger number resulting in higher floating point operations on the CPU and might cause lag during playback.</p><p>Howler.js is a great library that provides a wrapper around the audio api either in Web Audio API or Html5 for fallback purposes.</p><p>The ID3 tag I mentioned earlier can be read using jsmediatags library available in npm which let me extract the album art, artist name, and track details.</p><p>The intermediate result looks like as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*_IZVDz3KPYpiJissDoz7Vw.png" /><figcaption>Electron audio player</figcaption></figure><p>The source code is available on GitHub at:</p><p><a href="https://github.com/Sr-vZ/audioPlayer">Sr-vZ/audioPlayer</a></p><p>Feel free to fork and add features and improve the project.</p><p>If you find this article helpful please feel free to clap or follow me this will inspire me a lot!</p><p>If you want to support my efforts, please buy me a coffee!</p><figure><a href="https://www.buymeacoffee.com/srvzblogs"><img alt="buy me a coffee" src="https://cdn-images-1.medium.com/max/1024/1*tEuYZbZRIkPUieOP3nReNg.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1b133776c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>