tesyer tteahn
tesyer tteahn

Reputation: 23

creating scheduled tasks using python subprocess

I have problem with creating scheduled tasks with python. After executing my command, scheduled task's action part splits into argument and path slices and makes it invalid. I have tried lots of ways like "\" mypath \"" but was not successful. How can I concatenate executable's path to variable that makes scheduled task's task action valid ?

IMG-1: After creating scheduled task using script. Action path is invalid.

import os
import subprocess


path = os.environ['APPDATA']
filename = "test.exe"
path = path+"\\"+filename

command = 'schtasks.exe /CREATE /RU "%USERNAME%" /SC ONLOGON /TN "testServiceHello" /TR "'+path+'"'


proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout_value = proc.stdout.read() + proc.stderr.read()
print stdout_value
print "--"*50
print command

Upvotes: 2

Views: 2479

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140276

Even if the command line sounds OK, you should rely on parameter list, not parameter as string. Let popen do the heavy lifting and quote your parameters properly instead of trying to do it yourself.

I'd rewrite that as follows (and would drop shell=True, and merge the stdout+stderr from subprocess.Popen directly to avoid potential deadlocks)

command = ['schtasks.exe','/CREATE','/RU',os.getenv("USERNAME"),'/SC','ONLOGON','/TN','testServiceHello','/TR',os.path.join(os.environ['APPDATA'],"test.exe")]
proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout_value = proc.stdout.read()

you can print what subprocess will issue as a command like this:

subprocess.list2cmdline(command)

In your case, you have an extra problem because there seems to be a limitation in schtasks.exe. So the workaround would be to compute windows short path (lifted from this SO question)

import win32api
long_file_name=os.path.join(os.environ['APPDATA'],"test.exe")
short_file_name=win32api.GetShortPathName(long_file_name)
command = ['schtasks.exe','/CREATE','/RU',os.getenv("USERNAME"),'/SC','ONLOGON','/TN','testServiceHello','/TR',short_file_name]

and go on with the subprocess call

Upvotes: 2

Related Questions