Run a WSL-2 Ubuntu script on Windows 10 using Task Scheduler

877 views Asked by At
  • I'm running Windows 10 Enterprise (22H2)

  • I've installed Ubuntu 20.04 via WSL2

  • I've written a Python script, to be run within Ubuntu, that accepts input.

  • I've configured the Windows Task Scheduler to call the script once a day using the command ... C:\Windows\System32\wsl.exe "python3 /mnt/c/Users/.../automatic_temp_to_spreadsheet.py"'

  • Task Scheduler does start the task, and a terminal windows appears on my screen (as desired) however the prompts for input do not appear within the window, and hitting return simply closes the window. The window shows nothing in it (not even error messages.)

Attempting to run the script from the Windows command prompt using the above fails. It can't find the file, regardless of whether I try the Ubuntu path or the windows path.

C:\>C:\Windows\System32\wsl.exe
user@ubuntumachinename:/$ # This is OK. 

C:\>C:\Windows\System32\wsl.exe "python3"
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> #This is OK too

C:\>C:\Windows\System32\wsl.exe "python3 /mnt/c/Users/.../automatic_temp_to_spreadsheet.py"
/bin/bash: python3 /mnt/c/Users/.../automatic_temp_to_spreadsheet.py: No such file or directory

C:\>C:\Windows\System32\wsl.exe "C:\Users\...\automatic_temp_to_spreadsheet.py"
/bin/bash: C:\Users\...\automatic_temp_to_spreadsheet.py: command not found

Note the script works if I run it directly from an Ubuntu WSL terminal window.

user@ubuntumachinename:~$ python3 ./automatic_temp_to_spreadsheet.py
Opening /mnt/c/Users/.../Heat tracking.csv...OK (5)
How many pieces of wood burned today(int)?
(Etc...)
1

There are 1 answers

0
RightmireM On

OK.

The answer was to add a shebang to the start of the script and removing the "python3" at beginning.

So at the first line of the python script...

#!/usr/bin/env python3

And then change the command to...

C:\Windows\System32\wsl.exe -e "/mnt/c/Users/.../automatic_temp_to_spreadsheet.py"

enter image description here