[Tut] How to Schedule a Batch 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 Schedule a Batch Python Script (/thread-100219.html) |
[Tut] How to Schedule a Batch Python Script - xSicKxBot - 11-12-2022 How to Schedule a Batch Python Script <div> <div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{"align":"left","id":"880057","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>During your career as a Pythonista, you will encounter situations where a Python script will need to be executed on a scheduled basis, such as daily, weekly, or monthly. </p> <p>This article shows you how to accomplish this task using a <a rel="noreferrer noopener" href="https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands" data-type="URL" data-id="https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands" target="_blank"><code>.bat</code></a> (batch) file.</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 run a <code>.bat</code> (batch) file on a schedule<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>Create a Python Script</li> <li> Create a <code>.bat</code> File</li> <li> Execute a <code>.bat</code> File</li> <li> Schedule a <code>.bat</code> File Using Windows Task Scheduler</li> <li>Bonus: Schedule a Monthly <code>.bat</code> File</li> </ol> <hr class="wp-block-separator has-alpha-channel-opacity wp-embed-aspect-16-9 wp-has-aspect-ratio"/> <h2>Create a Python Script</h2> <p class="has-global-color-8-background-color has-background">Let’s first start by creating a Python script that counts down from five (5) to one (1).</p> <p>In the current working directory, create a Python file called <code>counter.p</code>y. 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="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from time import sleep lift_off = 5 while lift_off > 0: print (f'Lift Off in {lift_off} seconds!') sleep(2) lift_off -= 1</pre> <p>The first line in the above code snippet imports the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/time.html" data-type="URL" data-id="https://docs.python.org/3/library/time.html" target="_blank"><code>time</code></a> library. This allows access to the <a rel="noreferrer noopener" href="https://blog.finxter.com/time-delay-in-python/" data-type="URL" data-id="https://blog.finxter.com/time-delay-in-python/" target="_blank"><code>sleep()</code></a> function, which pauses the script between iterations.</p> <p>Next, a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>while</code></a> loop is instantiated and executes the code inside this loop until the value of <code>lift_off</code> is zero (0). </p> <p>On each iteration, the following occurs:</p> <ul> <li>A line of text is output to the terminal indicating the value of <code>lift_off</code>.</li> <li>The script pauses for two (2) seconds.</li> <li>The value of <code>lift_off</code> is decreased by one (1).</li> </ul> <p>To confirm script runs successfully. Navigate to the command prompt and run the following:</p> <pre class="wp-block-preformatted"><code>python counter.py</code></pre> <p>The output from this script should be as follows:</p> <pre class="wp-block-preformatted"><code>Lift Off in 5 seconds! Lift Off in 4 seconds! Lift Off in 3 seconds! Lift Off in 2 seconds! Lift Off in 1 seconds!</code></pre> <p>Great! Now let’s create a <code><code><a rel="noreferrer noopener" href="https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands" data-type="URL" data-id="https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands" target="_blank">.bat</a></code></code> (Batch) file to run this script!</p> <figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-schedule-a-batch-python-script/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_PG0pg7NT1Q%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Create a .bat File</h2> <p class="has-global-color-8-background-color has-background">This section creates a <code>.bat</code> file that executes <code>counter.py</code> by calling this file inside the <code>.bat</code> file.</p> <p>In the current working directory, create a Python file called <code>counter.bat</code>. Copy and paste the code snippet below into this file and save it.</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="">@echo off "C:\Python\python.exe" "C:\PYTHON_CODE\counter.py"</pre> <p>The first line of the code snippet turns off any output to the terminal (except the code inside <code>counter.py</code>). For example, If the first line (<code>@echo off</code>) was removed and <code>counter.bat</code> was executed, the following would be output to the terminal.</p> <pre class="wp-block-preformatted"><code>C:\WORK> "C:\Python\python.exe" "C:\PYTHON_CODE\counter.py" Lift Off in 5 seconds! Lift Off in 4 seconds! Lift Off in 3 seconds! Lift Off in 2 seconds! Lift Off in 1 seconds!</code></pre> <p>The following line of code specifies the following:</p> <ul> <li>The location of the <code>python.exe</code> file on your computer.</li> <li>The location of the python script to execute.</li> </ul> <p>Let’s see if this works!</p> <p class="has-global-color-8-background-color has-background"><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;" /> <strong>Note</strong>: It is best practice to ensure that the full paths to the <code>python.exe</code> and <code>counter.py</code> files are added. </p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Execute a .bat File</h2> <p class="has-global-color-8-background-color has-background">This section executes the <code><a rel="noreferrer noopener" href="https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands" data-type="URL" data-id="https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands" target="_blank">.bat</a></code> file created earlier. This code calls and executes the code inside the <code>counter.py</code> file.</p> <p>To run the <code><code><a rel="noreferrer noopener" href="https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands" data-type="URL" data-id="https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands" target="_blank">.bat</a></code></code> file, navigate to the IDE, and click to select and highlight the <code>counter.bat</code> file. Then, press the <code>F5</code> key on the keyboard to execute.</p> <p>If successful, the output should be the same as running the <code>counter.py</code> file directly.</p> <pre class="wp-block-preformatted"><code>Lift Off in 5 seconds! Lift Off in 4 seconds! Lift Off in 3 seconds! Lift Off in 2 seconds! Lift Off in 1 seconds!</code></pre> <p>Perfect! Let’s schedule this to run Daily at a specified time.</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Schedule a .bat File Using Windows Task Scheduler</h2> <p class="has-global-color-8-background-color has-background">This example uses Windows Task Scheduler to schedule a <code><code><a rel="noreferrer noopener" href="https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands" data-type="URL" data-id="https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands" target="_blank">.bat</a></code></code> file to run at a specified date/time.</p> <p>To set up a Task Scheduler on Windows, navigate to the command prompt from Windows and run the following code:</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="">taskschd.msc</pre> <p>Alternatively, click the Windows start button, search for, and select Task Scheduler.</p> <p>Either of the above actions will display the Task Scheduler pop-up.</p> <p>From the Actions area, click Create Basic Task. This action displays the Create a Basic Task Wizard pop-up.</p> <div class="wp-block-image"> <figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2022/11/bat_001a-1.png" alt="" class="wp-image-882608" width="572" height="399" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/bat_001a-1.png 779w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_001a-1-300x210.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_001a-1-768x537.png 768w" sizes="(max-width: 572px) 100vw, 572px" /></figure> </div> <p>From the Create a Basic Task pop-up, enter a Name and Description into the appropriate text boxes. Click the Next button to continue.</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_002.png" alt="" class="wp-image-882611" width="592" height="343" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/bat_002.png 687w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_002-300x174.png 300w" sizes="(max-width: 592px) 100vw, 592px" /></figure> </div> <p>This action displays the Task Trigger pop-up. Select when to run the <code>.bat</code> file. For this example, Daily was chosen. Click the Next button to continue.</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_003.png" alt="" class="wp-image-882616" width="611" height="354" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/bat_003.png 687w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_003-300x174.png 300w" sizes="(max-width: 611px) 100vw, 611px" /></figure> </div> <p>Since Daily was selected earlier, the Daily pop-up displays. Modify the fields to meet the desired date and time requirements. Click the Next button to continue.</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_004.png" alt="" class="wp-image-882625" width="612" height="354" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/bat_004.png 688w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_004-300x174.png 300w" sizes="(max-width: 612px) 100vw, 612px" /></figure> </div> <p>This action displays the Action pop-up. Select Start a program. Click the Next button to continue.</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-1.png" alt="" class="wp-image-882631" width="625" height="362" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/bat_005-1.png 688w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_005-1-300x174.png 300w" sizes="(max-width: 625px) 100vw, 625px" /></figure> </div> <p>This action displays the Start a Program pop-up. Browse to select the <code>counter.bat</code> file created earlier. Click the <code>Next</code> button to continue.</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_006.png" alt="" class="wp-image-882664" width="642" height="369" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/bat_006.png 692w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_006-300x173.png 300w" sizes="(max-width: 642px) 100vw, 642px" /></figure> </div> <p>This action displays the Summary pop-up. If satisfied with the selections made earlier, click the Finish button to complete the setup.</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/doner-001a.png" alt="" class="wp-image-885541" width="653" height="457" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/doner-001a.png 689w, https://blog.finxter.com/wp-content/uploads/2022/11/doner-001a-300x210.png 300w" sizes="(max-width: 653px) 100vw, 653px" /></figure> </div> <p>Great! The task is now scheduled to run at the date/time specified.</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2><strong><mark class="has-inline-color has-contrast-color">View, Edit, or Delete a Scheduled Task</mark></strong></h2> <p>To view a list of Scheduled Tasks, navigate to the Task Scheduler pop-up and select Task Scheduler Library.</p> <div class="wp-block-image"> <figure class="aligncenter size-large is-resized"><img decoding="async" loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2022/11/bat_007-1024x522.png" alt="" class="wp-image-882669" width="642" height="326" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/bat_007-1024x522.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_007-300x153.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_007.png 1057w" sizes="(max-width: 642px) 100vw, 642px" /></figure> </div> <p>To delete a task, click to select the appropriate task from the list of scheduled events. Then click the <strong>Delete</strong> link on the right-hand side.</p> <p>To edit a task, click to select the appropriate task from the list of scheduled events. Then click the Properties link on the right-hand side to display the Properties pop-up. From this pop-up, all of the above selections can be modified.</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_008.png" alt="" class="wp-image-882687" width="620" height="471" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/bat_008.png 620w, https://blog.finxter.com/wp-content/uploads/2022/11/bat_008-300x228.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></figure> </div> <p>Click the OK button to confirm any changes and close the pop-up.</p> <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>: We recommend you review the fields on each tab to learn more about scheduling tasks.</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Bonus: Schedule a Monthly .bat File</h2> <p class="has-global-color-8-background-color has-background">This section <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> containing sales data. This data is then sorted and filtered based on the current month. This is scheduled to run on the first day of each month. To follow along, <a rel="noreferrer noopener" 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">download</a> the CSV file.</p> <p>In the current working directory, create a Python file called <code>sales.py</code>. 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="" 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>In the current working directory, create a Python file called <code>sales.bat</code> Copy and paste the code snippet below into this file and save it. Modify to meet your locations.</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="">@echo off "C:\Python\python.exe" "C:\PYTHON_CODE\sales.py"</pre> <p>Let’s set up a Monthly schedule to run on the first day of each month by performing the following steps:</p> <ul> <li>Start the <strong>Windows Task Scheduler</strong>.</li> <li>From the <strong>Task Scheduler</strong> pop-up, select <strong>Create Basic Task</strong> from the <strong>Actions</strong> area.</li> <li>From the <strong>Create a Basic Task</strong> pop-up, enter a <strong>Name</strong> and <strong>Description</strong> in the appropriate text boxes. Click the <strong>Next</strong> button to continue.</li> <li>From the <strong>Task Trigger</strong> pop-up, select <strong>Monthly</strong>. Click the <strong>Next</strong> button to continue.</li> <li>From the <strong>Monthly</strong> pop-up, complete the fields as outlined below: <ul> <li>A Start Date and Start Time.</li> <li>From the <strong>Months</strong> dropdown, select each month that the report will run. For this example, all months were selected.</li> <li>From the <strong>Days</strong> dropdown, select the day(s) of the month to run this report. For this example, 1 was selected. </li> <li>Click the <strong>Next</strong> button to continue.</li> </ul> </li> <li>From the <strong>Action</strong> pop-up, select Start a Program. Click the Next button to continue.</li> <li>From the <strong>Start a Program</strong> pop-up, click the Browse button to locate and select the <code>sales.bat</code> file.</li> <li>From the <strong>Summary</strong> window click the <strong>Finish</strong> button. </li> </ul> <p>This completes the configuration and activates the Scheduler to run on the specified day/time.</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><code><code>.bat</code></code></code> file that executes a Python script on a scheduled basis. </p> <p>Good Luck & Happy Coding!</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Programming Humor – Python</h2> <div class="wp-block-image"> <figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="518" height="588" src="https://blog.finxter.com/wp-content/uploads/2022/07/image-65.png" alt="" class="wp-image-471102" srcset="https://blog.finxter.com/wp-content/uploads/2022/07/image-65.png 518w, https://blog.finxter.com/wp-content/uploads/2022/07/image-65-264x300.png 264w" sizes="(max-width: 518px) 100vw, 518px" /><figcaption><em>“I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I’m leaving you.”</em> — <a rel="noreferrer noopener" href="https://imgs.xkcd.com/comics/python.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/python.png" target="_blank">xkcd</a></figcaption></figure> </div> <hr class="wp-block-separator has-alpha-channel-opacity"/> </div> https://www.sickgaming.net/blog/2022/11/11/how-to-schedule-a-batch-python-script/ |