Search code examples
pythonwindowswindows-task-scheduler

How to pass variable in os.system


I am making a python program which will assign a task to the task scheduler (on Windows) to run a command once at a specific time.

I have a command, say, command1 = "C:\Windows\System32\calc.exe" and I have a task name say, cmd_name = "calculator" Now, I am passing these two variables in os.system(r'SchTasks /Create /SC ONCE /TN '+cmd_name+' /TR '+cmd+' /ST 17:28')

But, the task does not get scheduled.

I have referred to this question, this, and this link, but all of these do not help me as I am not passing a string as a whole in os.system(), instead there is an extra r in my command.

How do I pass these variables? I can also try any other method (using python) if someone suggest to schedule the task at a specific time.


Solution

  • I solved it using subprocess

    import os
    import subprocess
    command1 = "C:\Windows\System32\calc.exe"
    cmd_name = "calculator"
    cmd = 'SchTasks /Create /SC ONCE /TN "'+cmd_name+'" /TR "'+command1+'" /ST 18:24'
    subprocess.run(cmd)