[Tut] How to Create and Run a Batch File That Runs a Python Script? - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Create and Run a Batch File That Runs a Python Script? (/thread-100205.html) |
[Tut] How to Create and Run a Batch File That Runs a Python Script? - xSicKxBot - 11-09-2022 How to Create and Run a Batch File That Runs a Python Script? <div> <div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{"align":"left","id":"871359","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"1","readonly":"","score":"5","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}'> <div class="kksr-stars"> <div class="kksr-stars-inactive"> <div class="kksr-star" data-star="1" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="2" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="3" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="4" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="5" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> <div class="kksr-stars-active" style="width: 142.5px;"> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> </div> <div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div> </div> <h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Problem Formulation and Solution Overview</h2> <p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">This article will show you how to create and execute a batch file in Python.</p> <p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2139.png" alt="ℹ" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Info</strong>: A batch or <code>.bat</code> file is a file that contains commands to be executed in the order specified. This file type can organize and automate tasks that need to be run regularly without requiring user input. These files can be created using a text editor, such as Notepad.</p> <p>To make it more interesting, we have the following running scenario:</p> <p class="wp-embed-aspect-16-9 wp-has-aspect-ratio"><em>The Sales Manager of Suppliworks has asked you to create and send him a Monthly Sales Report. This file will arrive as an unsorted, unfiltered CSV. You will need to filter this criterion based on the current month and save it as an Excel file to the current working directory.</em></p> <p>Download the <a href="https://blog.finxter.com/wp-content/uploads/2022/11/sales.csv" data-type="URL" data-id="https://blog.finxter.com/wp-content/uploads/2022/11/sales.csv" target="_blank" rel="noreferrer noopener"><code>sales.csv</code></a> file to follow along with our article.</p> <hr class="wp-block-separator has-alpha-channel-opacity wp-embed-aspect-16-9 wp-has-aspect-ratio"/> <p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would we write code to create and execute a batch file in Python<em>?</em></p> <p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">We can accomplish this task by completing the following steps:</p> <ol type="video" class="wp-embed-aspect-16-9 wp-has-aspect-ratio"> <li>Install the Batch Runner Extension</li> <li>Create the Python Script</li> <li>Create the <code>.bat</code> file</li> <li>Execute</li> </ol> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Install Batch Runner Extension</h2> <p class="has-global-color-8-background-color has-background">To run/execute a <code>bat</code> file, an extension will need to be installed in the IDE.</p> <p>To install this extension, navigate to the IDE, <code>Extensions</code> area. In the <a rel="noreferrer noopener" href="https://code.visualstudio.com/" data-type="URL" data-id="https://code.visualstudio.com/" target="_blank">VSC</a> IDE, this can be found on the far left panel bar shown below.</p> <p>In the <em>Search</em> textbox, enter <em>Batch Runner</em>. While entering this text, the IDE automatically searches for extensions that match the criteria entered.</p> <p>Once the desired extension is found, click the <em>Install </em>button to the left of the Batch Runner extension to start the installation process.</p> <div class="wp-block-image"> <figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="380" src="https://blog.finxter.com/wp-content/uploads/2022/11/bat_001aa-1024x380.png" alt="" class="wp-image-874489" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/bat_001aa-1024x380.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_001aa-300x111.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_001aa-768x285.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_001aa.png 1188w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> </div> <p>Once the installation has been completed, the <em>Install</em> button converts to a Settings icon. The extension is now ready to use!</p> <div class="wp-block-image"> <figure class="aligncenter size-large"><img decoding="async" loading="lazy" width="1024" height="253" src="https://blog.finxter.com/wp-content/uploads/2022/11/bat_002a-1024x253.png" alt="" class="wp-image-874510" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/bat_002a-1024x253.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_002a-300x74.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_002a-768x190.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_002a.png 1312w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> </div> <p class="has-global-color-8-background-color has-background"><strong><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Note</strong>: Feel free to install the Batch Extension of your choosing.</p> <hr class="wp-block-separator has-text-color has-base-3-color has-alpha-channel-opacity has-base-3-background-color has-background"/> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Create Python Script</h2> <p class="has-global-color-8-background-color has-background">This section creates a Python file that <a href="https://blog.finxter.com/read-a-csv-file-to-a-pandas-dataframe/" data-type="post" data-id="440655" target="_blank" rel="noreferrer noopener">reads in a CSV</a>, sorts, filters and saves the output to an Excel file.</p> <p>You can replace this with any Python file you want to run. For this example, we’ll need two libraries:</p> <ul> <li>The <a rel="noreferrer noopener" href="https://blog.finxter.com/category/pandas-library/" data-type="URL" data-id="https://blog.finxter.com/category/pandas-library/" target="_blank"><code>pandas</code></a> library will need to be installed for this example, as the code reads in and filters a CSV file.</li> <li>The <code><a rel="noreferrer noopener" href="https://openpyxl.readthedocs.io/en/stable/" data-type="URL" data-id="https://openpyxl.readthedocs.io/en/stable/" target="_blank"><code>openpyxl</code></a></code> library will need to be installed for this example, as the code exports the filtered <a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-dataframe-to_excel-method/" data-type="post" data-id="344278" target="_blank">DataFrame to an Excel</a> file. To install <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-openpyxl-in-python/" data-type="post" data-id="457066" target="_blank">this library</a>, navigate to the IDE terminal command prompt. Enter and run the code snippet shown below.</li> </ul> <p>To install those libraries, navigate to the IDE terminal command prompt. Enter and run the two commands to install both libraries:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install pandas pip install openpyxl</pre> <p>In the current working directory, create a Python file called <code>sales.py</code>. </p> <p>Copy and paste the code snippet below into this file and save it.</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="5-6, 8-10, 12-13" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd from datetime import datetime import openpyxl today = datetime.now() cols = ['OrderDate', 'Region', 'Item', 'Units'] df = pd.read_csv('sales.csv', usecols=cols) df["OrderDate"] = pd.to_datetime(df["OrderDate"]) df = df.sort_values(by=['OrderDate']) df_monthly = df[df['OrderDate'].dt.month == today.month] df_monthly.to_excel('monthly_rpt.xlsx', columns=cols, index=False, header=True)</pre> <p>The first three (3) lines in the above code snippet import references to the libraries necessary to run this code error-free.</p> <p>The following line retrieves the current date using <code><a rel="noreferrer noopener" href="https://blog.finxter.com/get-the-current-time-python/" data-type="URL" data-id="https://blog.finxter.com/get-the-current-time-python/" target="_blank">datetime.now()</a> </code>from the <a rel="noreferrer noopener" href="https://blog.finxter.com/working-with-date-time-in-pandas/" data-type="URL" data-id="https://blog.finxter.com/working-with-date-time-in-pandas/" target="_blank"><code>datetime</code></a> library. The results save to the variable <code>today</code>. If the contents were output to the terminal, the following displays:</p> <pre class="wp-block-preformatted"><code>2022-11-08 07:59:00.875656</code></pre> <p>The next line declares a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">List</a> containing the DataFrame Columns to retrieve from the CSV file and export to the Excel file. The results save to <code>cols</code>.</p> <p>Then, the <code>sales.csv</code> file is opened, and columns specified in <code>cols</code> are retrieved. The results save to the DataFrame <code>df</code>. If <code>df</code> was output to the terminal, the following snippet displays:</p> <p><strong>Top Five (5) Records of <code>sales.csv</code> </strong></p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td></td> <td>OrderDate</td> <td>Region</td> <td>Item</td> <td>Units</td> </tr> <tr> <td>0</td> <td>11/6/2022</td> <td>East</td> <td>Pencil</td> <td>95</td> </tr> <tr> <td>1</td> <td>11/23/2022</td> <td>Central</td> <td>Binder</td> <td>50</td> </tr> <tr> <td>2</td> <td>11/9/2022</td> <td>Central</td> <td>Pencil</td> <td>36</td> </tr> <tr> <td>3</td> <td>11/26/2022</td> <td>Central</td> <td>Pen</td> <td>27</td> </tr> <tr> <td>4</td> <td>11/15/2022</td> <td>West</td> <td>Pencil</td> <td>56</td> </tr> </tbody> </table> </figure> <p>The next line converts the <code>OrderDate</code> into a proper Date format.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td></td> <td>OrderDate</td> <td>Region</td> <td>Item</td> <td>Units</td> </tr> <tr> <td>0</td> <td><strong>2022-11-06</strong></td> <td>East</td> <td>Pencil</td> <td>95</td> </tr> <tr> <td>1</td> <td><strong>2022-11-23</strong></td> <td>Central</td> <td>Binder</td> <td>50</td> </tr> <tr> <td>2</td> <td><strong>2022-11-09</strong></td> <td>Central</td> <td>Pencil</td> <td>36</td> </tr> <tr> <td>3</td> <td><strong>2022-11-26</strong></td> <td>Central</td> <td>Pen</td> <td>27</td> </tr> <tr> <td>4</td> <td><strong>2022-11-15</strong></td> <td>West</td> <td>Pencil</td> <td>56</td> </tr> </tbody> </table> </figure> <p>As you can see, the DataFrame, <code>df</code>, is not in any kind of sort order. The next line takes care of this by sorting on the <code>OrderDate</code> field in ascending order. The results save back to the DataFrame <code>df</code>. </p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td></td> <td>OrderDate</td> <td>Region</td> <td>Item</td> <td>Units</td> </tr> <tr> <td>22</td> <td><strong>2022-01-15</strong></td> <td>Central</td> <td>Binder</td> <td>46</td> </tr> <tr> <td>23</td> <td><strong>2022-02-01</strong></td> <td>Central</td> <td>Binder</td> <td>87</td> </tr> <tr> <td>24</td> <td><strong>2022-02-18</strong></td> <td>East</td> <td>Binder</td> <td>4</td> </tr> <tr> <td>25</td> <td><strong>2022-03-07</strong></td> <td>West</td> <td>Binder</td> <td>7</td> </tr> <tr> <td>26</td> <td><strong>2022-03-24</strong></td> <td>Central</td> <td>Pen Set</td> <td>50</td> </tr> </tbody> </table> </figure> <p>This script’s final two (2) lines filter the DataFrame, <code>df</code>, based on the current month. The results save to <code>df_monthly</code>. These results are then exported to Excel and placed into the current working directory.</p> <p>If you run this code, you will see that the Excel file saved the appropriate filtered results into the <code>monthly_rpt.xlsx</code> file.</p> <div class="wp-block-image"> <figure class="aligncenter size-full is-resized"><img decoding="async" loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2022/11/bat_005.png" alt="" class="wp-image-876363" width="611" height="276" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/bat_005.png 621w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_005-300x135.png 300w" sizes="(max-width: 611px) 100vw, 611px" /></figure> </div> <p>Great! Now let’s create a Batch file to run this script!</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Create Batch File</h2> <p class="has-global-color-8-background-color has-background">In this section, a <code>bat</code> file is created to run the Python file <code>sales.py</code>.</p> <p>In the current working directory, create a <code>bat</code> file called <code>sales.bat</code>. </p> <p>Copy and paste the code snippet below into this file and save it.</p> <pre class="EnlighterJSRAW" data-enlighter-language="bat" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@echo off "C:\Python\python.exe" "sales.py"</pre> <p>The first line of the code snippet turns off any output to the terminal.</p> <p>The following line specifies the following:</p> <ul> <li>The location of the <code>python.exe</code> file on your computer.</li> <li>The Python script to execute.</li> </ul> <p>Let’s see if this works!</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Execute</h2> <p class="has-global-color-8-background-color has-background">This section executes the <code>bat</code> file, which calls and runs the code inside the <code>sales.py</code> file.</p> <p>To run the <code>bat</code> file, navigate to the IDE, and click to select the <code>sales.bat</code> file.</p> <p>Press the <code>F5</code> key on the keyboard to execute.</p> <p>If successful, the <code>monthly_rpt.xlsx</code> file will appear in the current working directory!</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Summary</h2> <p>This article has shown you have to create and run a <code>.bat</code> file that executes a Python script. This file can execute a simple Python script as well as an intricate one.</p> <p>Good Luck & Happy Coding!</p> <hr class="wp-block-separator has-alpha-channel-opacity"/></p> </div> https://www.sickgaming.net/blog/2022/11/08/how-to-create-and-run-a-batch-file-that-runs-a-python-script/ |