2

I created two file: one, main.py and the other, default.j2. When I run cmd from the folder "code" where both are located (main.py and default.j2,) it works fine, but I try to automate the script on Windows Task Scheduler, it displays "No template file present: default.j2" even though the template exists in the path/folder.

Below is the code I use to check to whether the path is found or not.

def render_template(template, **kwargs):
# check if template exists
if not os.path.exists(template):
    print('No template file present: %s' % template)
    sys.exit()

import jinja2
templateLoader = jinja2.FileSystemLoader(searchpath="")
templateEnv = jinja2.Environment(loader=templateLoader)
templ = templateEnv.get_template(template)

return templ.render(**kwargs)
aschultz
  • 1,658
  • 3
  • 20
  • 30
hanan
  • 532
  • 2
  • 7
  • 23

1 Answers1

2

This link notes that Windows Task Scheduler runs from c:\%WINDIR%\System32. So if you are just using the file name for the file with Task Scheduler, it will look for c:\%WINDIR%\System32\default.j2 instead of (code)\default.j2.

You can use

import os
os.chdir(code_dir)

(run your code)

Or you can try suggestions from here in case main.py's location may change in the future, or you have other files like this in other directories. Thus one option would be:

os.chdir(os.path.dirname(__file__))

Another option would be:

template = os.path.join(os.chdir(os.path.dirname(__file__)), "default.j2")
aschultz
  • 1,658
  • 3
  • 20
  • 30
  • 2
    thank you for the clarification. this has helped me :) – hanan Aug 05 '19 at 16:58
  • @hanan Glad I could help! I ran into the same problem several times w/Taskscheduler & likely will again--it's easy to forget the starting directory isn't the script file's directory. I don't know how familiar you are with python, but I highly recommend reading the OS documentation highly. I had a bunch of "Oh! I can do THAT?!" moments. It's helped with so much simple file/directory manipulation. The pathlib module is a bit more complex. – aschultz Aug 06 '19 at 03:08